package com.cq.hd.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cq.hd.common.constant.Constant;
import com.cq.hd.common.entity.mq.ActiveBrowseMsg;
import com.cq.hd.common.enums.ResponseEnums;
import com.cq.hd.common.enums.biz.*;
import com.cq.hd.common.exception.BusinessException;
import com.cq.hd.common.pagination.Page;
import com.cq.hd.common.response.Throw;
import com.cq.hd.common.utils.LocalDateUtil;
import com.cq.hd.common.utils.NoUtils;
import com.cq.hd.member.api.*;
import com.cq.hd.member.api.dto.ShareActivePointsDto;
import com.cq.hd.member.api.vo.*;
import com.cq.hd.order.api.TbOrderApi;
import com.cq.hd.order.api.TbOrderItemApi;
import com.cq.hd.order.api.dto.OrderDto;
import com.cq.hd.order.api.dto.OrderItemDto;
import com.cq.hd.order.api.vo.GroupBuyOrderNumStatVo;
import com.cq.hd.order.api.vo.OrderItemVo;
import com.cq.hd.order.api.vo.OrderVo;
import com.cq.hd.product.api.TbActiveApi;
import com.cq.hd.product.api.dto.*;
import com.cq.hd.product.api.vo.*;
import com.cq.hd.product.config.LockUtils;
import com.cq.hd.product.config.WxConfig;
import com.cq.hd.product.factory.ActiveReleaseFactory;
import com.cq.hd.product.mapper.*;
import com.cq.hd.product.mq.ActiveBrowseMsgProvider;
import com.cq.hd.product.po.*;
import com.cq.hd.product.processor.ActiveShareRewardProcessor;
import com.cq.hd.product.service.TbActiveGroupBuyService;
import com.cq.hd.product.service.TbActiveLabelService;
import com.cq.hd.product.service.TbActiveRedPacketBillService;
import com.cq.hd.product.service.TbActiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 活动表 服务实现类
 * </p>
 *
 * @author mYunYu
 * @since 2023-11-23
 */
@Slf4j
@Service
public class TbActiveServiceImpl extends ServiceImpl<TbActiveMapper, TbActivePo> implements TbActiveService {

    @Autowired
    private TbActiveDiscountMapper activeDiscountMapper;

    @Autowired
    private TbActiveStepPriceMapper activeStepPriceMapper;

    @Autowired
    private TbActiveRedPacketMapper activeRedPacketMapper;

    @Autowired
    private TbActiveRedPacketBillMapper activeRedPacketBillMapper;

    @Autowired
    private TbActiveGoodsMapper activeGoodsMapper;

    @Autowired
    private TbActiveGoodsSubsidyMapper activeGoodsSubsidyMapper;

    @Autowired
    private TbActiveAgentMapper activeAgentMapper;

    @Autowired
    private TbActiveEnrollInfoMapper activeEnrollInfoMapper;

    @Autowired
    private TbBusinessAgentApi businessAgentApi;

    @Autowired
    private TbBusinessSubscribeApi businessSubscribeApi;

    @Autowired
    private TbActiveBrowseMapper activeBrowseMapper;

    @Autowired
    private TbActiveBrowseStatisticsMapper activeBrowseStatisticsMapper;

    @Autowired
    private TbActiveCollectMapper activeCollectMapper;

    @Autowired
    private TbGoodsMapper goodsMapper;

    @Autowired
    private TbActiveShareMapper activeShareMapper;

    @Autowired
    private TbActiveGoodsStockMapper activeGoodsStockMapper;

    @Autowired
    private TbAppUserApi appUserApi;

    @Autowired
    private TbBusinessApi businessApi;

    @Autowired
    private TbMerchantApi merchantApi;

    @Autowired
    private TbOrderItemApi orderItemApi;

    @Autowired
    private TbOrderApi orderApi;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private ActiveBrowseMsgProvider activeBrowseMsgProvider;

    @Autowired
    private TbUserBusinessApi userBusinessApi;

    @Autowired
    private TbActiveLabelService activeLabelService;

    @Autowired
    private TbBusinessPointsMallApi businessPointsMallApi;

    @Autowired
    private TbActiveApi tbActiveApi;

    @Autowired
    private TbActiveRedPacketBillService activeRedPacketBillService;

    @Autowired
    private TbActiveGroupBuyService activeGroupBuyService;

    @Autowired
    private ActiveShareRewardProcessor activeShareRewardProcessor;

    @Override
    public Boolean checkGoodsStock(ActiveGoodsStockCheckDto activeGoodsStockCheckDto) {
        TbGoodsPo tbGoodsPo = goodsMapper.selectById(activeGoodsStockCheckDto.getGoodsId());
        Integer remainStock = tbGoodsPo.getRemainStock();
        return remainStock >= activeGoodsStockCheckDto.getGoodsNum() * activeGoodsStockCheckDto.getTotalStock();
    }



    @Override
    public Long releaseActive(ActiveReleaseDto activeReleaseDto) {
        // 活动类型(1-团购活动，2-报名活动，3-外部活动，4-团购+报名活动)
        setActiveType(activeReleaseDto);

        Long businessId = activeReleaseDto.getBusinessId();
        if (businessId == null || businessId <= 0) {
            Long userId = activeReleaseDto.getUserId();
            if (userId == null || userId <= 0) {
                Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
            }

            BusinessPageVo businessPageVo = businessApi.getByUserId(userId).unpack();
            if (businessPageVo == null) {
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            activeReleaseDto.setBusinessId(businessPageVo.getId());
        }

        Long id = activeReleaseDto.getId();
        if (id != null && id > 0) {
            TbActivePo activePo = baseMapper.selectById(id);
            if (activePo != null && !activePo.getBusinessId().equals(businessId)) {
                log.error("发布活动，没有操作权限，businessId：{}，activeBusinessId：{}", businessId, activePo.getBusinessId());
                Throw.isBusinessException("没有操作权限");
            }
        }

        String provinceName = activeReleaseDto.getProvinceName();
        if ("北京市".equals(provinceName) || "重庆市".equals(provinceName) || "上海市".equals(provinceName) || "天津市".equals(provinceName)) {
            activeReleaseDto.setCityName(provinceName);
        }

        return ActiveReleaseFactory.getActiveReleaseHandler(activeReleaseDto.getActiveType()).saveActiveData(activeReleaseDto);
    }

    @Override
    public Page<AppMyActivePageVo> pageMyActive(AppMyActivePageDto appMyActivePageDto) {
        Long userId = appMyActivePageDto.getUserId();
        if (userId == null || userId <= 0) {
            Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
        }

        Long businessId = appMyActivePageDto.getBusinessId();
        if (businessId == null || businessId <= 0) {
            BusinessPageVo businessPageVo = businessApi.getByUserId(userId).unpack();
            if (businessPageVo == null) {
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            appMyActivePageDto.setBusinessId(businessPageVo.getId());
        }

        LocalDateTime now = LocalDateTime.now();

        // 分页条件查询活动数据
        appMyActivePageDto.setNowTime(now);
        PageHelper.startPage(appMyActivePageDto.getPageNum(), appMyActivePageDto.getPageSize());
        List<AppMyActivePageVo> appMyActivePageVos = baseMapper.listMyActiveByDto(appMyActivePageDto);
        if (!CollectionUtils.isEmpty(appMyActivePageVos)) {
            List<Long> activeIds = appMyActivePageVos.stream().map(AppMyActivePageVo::getId).collect(Collectors.toList());
            List<Long> businessIds = appMyActivePageVos.stream().map(AppMyActivePageVo::getBusinessId).collect(Collectors.toList());

            // 查询多件多折列表
            Map<Long, List<ActiveDiscountSonDto>> tbActiveDiscountPoMap = new HashMap<>();
            List<ActiveDiscountSonDto> tbActiveDiscountPos = activeDiscountMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(tbActiveDiscountPos)) {
                tbActiveDiscountPoMap = tbActiveDiscountPos.stream().collect(Collectors.groupingBy(ActiveDiscountSonDto::getActiveId));
            }

            // 查询新人首单红包数据
            Map<Long, ActiveRedPacketSonDto> activeRedPacketSonDtoMap = new HashMap<>();
            List<ActiveRedPacketSonDto> activeRedPacketSonDtoList = activeRedPacketMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeRedPacketSonDtoList)) {
                activeRedPacketSonDtoMap = activeRedPacketSonDtoList.stream().collect(Collectors.toMap(ActiveRedPacketSonDto::getActiveId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询阶梯价格列表
            Map<Long, List<ActiveStepPriceSonDto>> activeStepPriceSonDtoMap = new HashMap<>();
            List<ActiveStepPriceSonDto> activeStepPriceSonDtos = activeStepPriceMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeStepPriceSonDtos)) {
                activeStepPriceSonDtoMap = activeStepPriceSonDtos.stream().collect(Collectors.groupingBy(ActiveStepPriceSonDto::getActiveId));
            }

            // 查询活动浏览数
            Map<Long, List<TbActiveBrowseStatisticsPo>> tbActiveBrowseStatisticsPoMap = new HashMap<>();
            List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPos = activeBrowseStatisticsMapper.selectList(new QueryWrapper<TbActiveBrowseStatisticsPo>()
                    .eq("del_state", 0)
                    .in("active_id", activeIds));
            if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPos)) {
                tbActiveBrowseStatisticsPoMap = tbActiveBrowseStatisticsPos.stream().collect(Collectors.groupingBy(TbActiveBrowseStatisticsPo::getActiveId));
            }

            // 根据活动id查询订单数据
            Map<Long, List<OrderVo>> orderMap = new HashMap<>();
            OrderDto orderDto = new OrderDto();
            orderDto.setActiveIds(activeIds);
            orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_VERIFY.getValue(),
                    OrderStateEnum.VERIFYING.getValue(),
                    OrderStateEnum.FINISH.getValue(),
                    OrderStateEnum.VERIFIED.getValue()));
            List<OrderVo> orderVos = orderApi.listByDto(orderDto).unpack();
            if (!CollectionUtils.isEmpty(orderVos)) {
                orderMap = orderVos.stream().collect(Collectors.groupingBy(OrderVo::getActiveId));
            }

            // 根据活动id查询订单项数据
            Map<Long, List<OrderItemVo>> orderItemMap = new HashMap<>();
            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setActiveIds(activeIds);
            orderItemDto.setSubOrderStates(Arrays.asList(SubOrderStateEnum.WAIT_VERIFY.getValue(),
                    SubOrderStateEnum.VERIFIED.getValue()));
            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
            if (!CollectionUtils.isEmpty(orderItemVos)) {
                orderItemMap = orderItemVos.stream().collect(Collectors.groupingBy(OrderItemVo::getActiveId));
            }

            for (AppMyActivePageVo appMyActivePageVo : appMyActivePageVos) {
                Long id = appMyActivePageVo.getId();
                List<ActiveDiscountSonDto> activeDiscountSonDtoList = tbActiveDiscountPoMap.get(id);
                if (!CollectionUtils.isEmpty(activeDiscountSonDtoList)) {
                    appMyActivePageVo.setActiveDiscount(activeDiscountSonDtoList);
                }

                ActiveRedPacketSonDto activeRedPacketSonDto = activeRedPacketSonDtoMap.get(id);
                if (activeRedPacketSonDto != null) {
                    appMyActivePageVo.setActiveRedPacket(activeRedPacketSonDto);
                }

                List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceSonDtoMap.get(id);
                if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
                    appMyActivePageVo.setActiveStepPrices(activeStepPriceSonDtoList);

                    // 将阶梯价格的最高价设置为活动价格显示
//                    appMyActivePageVo.setActivePrice(getMaxStepPrice(activeStepPriceSonDtoList));
                }

                // 对未开始和进行中的活动状态处理
                Integer activeState = appMyActivePageVo.getActiveState();
                if (ActiveStateEnum.NO_START.getValue().equals(activeState) || ActiveStateEnum.IN_PROGRESS.getValue().equals(activeState)) {
                    LocalDateTime startTime = appMyActivePageVo.getStartTime();
                    LocalDateTime endTime = appMyActivePageVo.getEndTime();

                    if (startTime.compareTo(now) > 0) {
                        appMyActivePageVo.setActiveState(ActiveStateEnum.NO_START.getValue());
                    } else if (endTime.compareTo(now) <= 0) {
                        appMyActivePageVo.setActiveState(ActiveStateEnum.ENDED.getValue());
                    } else if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
                        appMyActivePageVo.setActiveState(ActiveStateEnum.IN_PROGRESS.getValue());
                    }
                }

                List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPoList = tbActiveBrowseStatisticsPoMap.get(id);
                if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPoList)) {
                    appMyActivePageVo.setBrowseNum(tbActiveBrowseStatisticsPoList.stream().mapToLong(TbActiveBrowseStatisticsPo::getBrowseNum).sum());
                }

                // 成交数
                int tradeNum = 0;
                // 成交金额
                BigDecimal tradeAmt = BigDecimal.ZERO;
                // 分销订单数
                int distributeOrderNum = 0;
                // 分销佣金 = 活动结束前 统计预估佣金  活动结束后  统计实际结算佣金
                BigDecimal distributeOrderAmt = BigDecimal.ZERO;
                // 购买人数
                int buyNum = 0;

                List<OrderVo> orderVoList = orderMap.get(id);
                if (!CollectionUtils.isEmpty(orderVoList)) {
                    for (OrderVo orderVo : orderVoList) {
                        Long agentId = orderVo.getAgentId();
                        if (agentId != null && agentId > 0) {
                            // 分销订单数
                            distributeOrderNum += 1;
                        }

                        // 成交数
                        tradeNum += 1;
                        // 成交金额 = 实付金额
                        tradeAmt = tradeAmt.add(orderVo.getPayPrice());
                    }

                    // 购买人数
                    buyNum = orderVoList.stream().mapToInt(OrderVo::getOrderNum).sum();
                }

                List<OrderItemVo> orderItemVoList = orderItemMap.get(id);
                if (!CollectionUtils.isEmpty(orderItemVoList)) {
                    for (OrderItemVo orderItemVo : orderItemVoList) {
                        // 分销佣金=已支付订单需要给的佣金金额
                        distributeOrderAmt = distributeOrderAmt.add(orderItemVo.getCommissionAmt());
                    }
                }

                appMyActivePageVo.setTradeNum(tradeNum);
                appMyActivePageVo.setTradeAmt(tradeAmt);
                appMyActivePageVo.setDistributeOrderNum(distributeOrderNum);
                appMyActivePageVo.setDistributeOrderAmt(distributeOrderAmt);
                appMyActivePageVo.setBuyNum(buyNum + appMyActivePageVo.getSaleNum());
            }

            processBusinessActivesGroupBuyTag(appMyActivePageVos);

        }

        PageInfo<AppMyActivePageVo> pageInfo = new PageInfo<>(appMyActivePageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    private void processBusinessActivesGroupBuyTag(List<AppMyActivePageVo> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        List<Long> activeIds = dataList.stream()
                .filter(e -> PromotionTypeEnum.GROUP_BUY.name().equals(e.getPromotionType()))
                .map(AppMyActivePageVo::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activeIds)) {
            return;
        }
        Map<Long, TbActiveGroupBuyPo> activeIdToGroupBuyInfo = activeGroupBuyService.listByActiveIds(activeIds)
                .stream()
                .collect(Collectors.toMap(TbActiveGroupBuyPo::getActiveId, Function.identity()));
        for (AppMyActivePageVo pageVo : dataList) {
            TbActiveGroupBuyPo groupBuyInfo = activeIdToGroupBuyInfo.get(pageVo.getId());
            if (groupBuyInfo != null) {
                pageVo.setPromotionLabel(groupBuyInfo.getGroupNum() + "人团");
            }
        }
    }

    @Transactional
    @Override
    public boolean updateActive(ActiveUpdateDto activeUpdateDto) {
        TbActivePo tbActivePo = baseMapper.selectById(activeUpdateDto.getId());
        if (tbActivePo == null || tbActivePo.getDelState() != 0) {
            Throw.isBusinessException("未找到活动数据");
        }

        Integer activeType = tbActivePo.getActiveType();
        // 活动类型(1-团购活动，2-报名活动，3-外部活动)
        if (activeType == null || ActiveTypeEnum.typeOf(activeType) == null) {
            Throw.isBusinessException("活动类型值错误");
        }

        Long businessId = activeUpdateDto.getBusinessId();
        if (businessId == null || businessId <= 0) {
            Long userId = activeUpdateDto.getUserId();
            if (userId == null || userId <= 0) {
                Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
            }

            BusinessPageVo businessPageVo = businessApi.getByUserId(userId).unpack();
            if (businessPageVo == null) {
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            activeUpdateDto.setBusinessId(businessPageVo.getId());
        }

        if (!tbActivePo.getBusinessId().equals(businessId)) {
            log.error("修改活动，没有操作权限，businessId：{}，activeBusinessId：{}", businessId, tbActivePo.getBusinessId());
            Throw.isBusinessException("没有操作权限");
        }

        // 活动状态（1-未发布，2-未开始，3-进行中，4-已结束）
        Integer activeState = tbActivePo.getActiveState();
        if (ActiveStateEnum.ENDED.getValue().equals(activeState)) {
            Throw.isBusinessException("已结束的活动不能修改");
        }

        LocalDateTime now = LocalDateTime.now();

        // 判断未开始的活动是否是进行中还是已结束
        LocalDateTime startTime = tbActivePo.getStartTime();
        LocalDateTime endTime = tbActivePo.getEndTime();

        // 如果活动已结束，则不能修改
        if (endTime.compareTo(now) <= 0) {
            tbActivePo.setActiveState(ActiveStateEnum.ENDED.getValue());
            tbActivePo.setUpdateTime(now);
            int count = baseMapper.updateById(tbActivePo);
            if (count == 0) {
                Throw.isBusinessException("修改活动失败");
            }

//            Throw.isBusinessException("已结束的活动不能修改");
        }
        if (ActiveTypeEnum.ENROLL.getValue().equals(activeType) && VerifyTypeEnum.TYF.getValue().equals(activeUpdateDto.getVerifyType())) {
            if (StrUtil.isEmpty(activeUpdateDto.getPftProduct())) {
                Throw.isBusinessException("票付通产品ID不能为空");
            }
            if (StrUtil.isEmpty(activeUpdateDto.getPftTicket())) {
                Throw.isBusinessException("票付通门票ID不能为空");
            }
            if (StrUtil.isEmpty(activeUpdateDto.getPftSupplier())) {
                Throw.isBusinessException("票付通供应商ID不能为空");
            }
            boolean flag = orderApi.pftOrderPreCheck(activeUpdateDto.getPftSupplier()
                    , activeUpdateDto.getPftProduct(), activeUpdateDto.getPftTicket()).unpack();
            if (!flag) {
                Throw.isBusinessException("票付通参数设置有误，请确认后重试");
            }
        }

        // 如果活动状态是进行中，则仅可修改标题、图片、活动详情、活动结束时间；活动结束时间不可以小于当前时间；
        // 进行中：活动标题，活动图片，活动内容，活动结束时间，活动联系电话、客服微信
        if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
            String getEndTime = activeUpdateDto.getEndTime();
            if (StringUtils.isEmpty(getEndTime)) {
                Throw.isBusinessException("请设置活动时间");
            }

            LocalDateTime endTimeLocalDateTime = null;
            try {
                endTimeLocalDateTime = LocalDateUtil.toLocalDateTime(getEndTime, Constant.YYYY_MM_DD_HH_MM_SS);
            } catch (Exception e) {
                Throw.isBusinessException("活动结束时间设置有误");
            }

            if (endTimeLocalDateTime.compareTo(now) <= 0) {
                Throw.isBusinessException("活动结束时间不可以小于当前时间");
            }

            tbActivePo.setActiveTitle(activeUpdateDto.getActiveTitle());
            tbActivePo.setActiveImg(activeUpdateDto.getActiveImg());
            tbActivePo.setContent(CollectionUtils.isEmpty(activeUpdateDto.getActiveContents()) ? "" : JSON.toJSONString(activeUpdateDto.getActiveContents()));
            tbActivePo.setEndTime(endTimeLocalDateTime);
            if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
                tbActivePo.setActiveMobile(activeUpdateDto.getActiveMobile());
                tbActivePo.setActiveWechat(activeUpdateDto.getActiveWechat());
            }
            tbActivePo.setActiveState(ActiveStateEnum.IN_PROGRESS.getValue());
            tbActivePo.setUpdateTime(now);

            tbActivePo.setVerifyType(activeUpdateDto.getVerifyType());
            tbActivePo.setPftProduct(activeUpdateDto.getPftProduct());
            tbActivePo.setPftTicket(activeUpdateDto.getPftTicket());
            tbActivePo.setPftSupplier(activeUpdateDto.getPftSupplier());

            // 使用结束时间
            LocalDateTime validStartLocalDateTime = null;
            LocalDateTime validEndLocalDateTime = null;
            try {
                validStartLocalDateTime = LocalDateUtil.toLocalDateTime(activeUpdateDto.getValidStartTime(), Constant.YYYY_MM_DD_HH_MM_SS);
                validEndLocalDateTime = LocalDateUtil.toLocalDateTime(activeUpdateDto.getValidEndTime(), Constant.YYYY_MM_DD_HH_MM_SS);
            } catch (Exception e) {
                Throw.isBusinessException("使用时间设置有误");
            }

            // 活动有效开始时间，不能大于活动有效结束时间
            if (validStartLocalDateTime.compareTo(validEndLocalDateTime) >= 0) {
                Throw.isBusinessException("活动有效开始时间不能晚于活动有效结束时间");
            }
            tbActivePo.setAddress(activeUpdateDto.getAddress());
            tbActivePo.setValidStartTime(validStartLocalDateTime);
            tbActivePo.setValidEndTime(validEndLocalDateTime);
            // 下单限购
            tbActivePo.setLimitBuyNum(activeUpdateDto.getLimitBuyNum());
            tbActivePo.setLimitEnrollNum(activeUpdateDto.getLimitBuyNum());
            // 隐藏链接
            tbActivePo.setHideLink(activeUpdateDto.getHideLink());
            // 过期自动退款
            tbActivePo.setAutoRefundEnabled(activeUpdateDto.getAutoRefundEnabled());
            // 更新库存
            updateActiveGoodsStock(activeUpdateDto, tbActivePo);
            int count = baseMapper.updateById(tbActivePo);
            if (count == 0) {
                Throw.isBusinessException("修改活动失败");
            }

            return true;
        }

        // 如果活动还是未开始，则可以修改部分字段
        // 未开始：活动标题，活动图片，活动内容，活动时间，活动有效起止时间，活动地点，活动联系电话，活动客服微信号，活动链接
        if (startTime.compareTo(now) > 0) {
            // 校验活动时间
            String getStartTime = activeUpdateDto.getStartTime();
            String getEndTime = activeUpdateDto.getEndTime();
            String validStartTime = activeUpdateDto.getValidStartTime();
            String validEndTime = activeUpdateDto.getValidEndTime();

            if (StringUtils.isEmpty(startTime) || StringUtils.isEmpty(endTime)) {
                Throw.isBusinessException("请设置活动时间");
            }

            LocalDateTime startLocalDateTime = null;
            LocalDateTime endLocalDateTime = null;
            try {
                startLocalDateTime = LocalDateUtil.toLocalDateTime(getStartTime, Constant.YYYY_MM_DD_HH_MM_SS);
                endLocalDateTime = LocalDateUtil.toLocalDateTime(getEndTime, Constant.YYYY_MM_DD_HH_MM_SS);
            } catch (Exception e) {
                Throw.isBusinessException("活动时间设置有误");
            }

            // 活动开始时间，不能早于当前时间
            if (now.compareTo(startLocalDateTime) >= 0) {
                Throw.isBusinessException("活动开始时间不能早于当前时间");
            }

            // 活动开始时间，不能大于活动结束时间
            if (startLocalDateTime.compareTo(endLocalDateTime) >= 0) {
                Throw.isBusinessException("活动开始时间不能晚于活动结束时间");
            }

            if (endLocalDateTime.compareTo(now) <= 0) {
                Throw.isBusinessException("活动结束时间不可以小于当前时间");
            }

            if (ActiveTypeEnum.GROUP.getValue().equals(activeType)
                    || ActiveTypeEnum.ENROLL.getValue().equals(activeType)
                    || ActiveTypeEnum.GROUP_ENROLL.getValue().equals(activeType)) {
                if (StringUtils.isEmpty(validStartTime) || StringUtils.isEmpty(validEndTime)) {
                    Throw.isBusinessException("请设置使用时间");
                }

                LocalDateTime validStartLocalDateTime = null;
                LocalDateTime validEndLocalDateTime = null;
                try {
                    validStartLocalDateTime = LocalDateUtil.toLocalDateTime(validStartTime, Constant.YYYY_MM_DD_HH_MM_SS);
                    validEndLocalDateTime = LocalDateUtil.toLocalDateTime(validEndTime, Constant.YYYY_MM_DD_HH_MM_SS);
                } catch (Exception e) {
                    Throw.isBusinessException("使用时间设置有误");
                }

                // 活动有效开始时间，不能大于活动有效结束时间
                if (validStartLocalDateTime.compareTo(validEndLocalDateTime) >= 0) {
                    Throw.isBusinessException("活动有效开始时间不能晚于活动有效结束时间");
                }

                // 活动结束时间，不能大于活动有效开始时间
//                if (endLocalDateTime.compareTo(validStartLocalDateTime) >= 0) {
//                    Throw.isBusinessException("活动结束时间不能晚于活动有效开始时间");
//                }

                tbActivePo.setValidStartTime(validStartLocalDateTime);
                tbActivePo.setValidEndTime(validEndLocalDateTime);
            }

            if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
                tbActivePo.setActiveMobile(activeUpdateDto.getActiveMobile());
                tbActivePo.setActiveWechat(activeUpdateDto.getActiveWechat());
            }

            if (ActiveTypeEnum.EXTERNAL.getValue().equals(activeType)) {
                if (StringUtils.isEmpty(activeUpdateDto.getActiveUrl())) {
                    Throw.isBusinessException("请填写活动链接");
                }
                tbActivePo.setActiveUrl(activeUpdateDto.getActiveUrl());
            }

            tbActivePo.setActiveTitle(activeUpdateDto.getActiveTitle());
            tbActivePo.setActiveImg(activeUpdateDto.getActiveImg());
            tbActivePo.setContent(CollectionUtils.isEmpty(activeUpdateDto.getActiveContents()) ? "" : JSON.toJSONString(activeUpdateDto.getActiveContents()));
            tbActivePo.setStartTime(startLocalDateTime);
            tbActivePo.setEndTime(endLocalDateTime);
            tbActivePo.setAddress(activeUpdateDto.getAddress());
            tbActivePo.setUpdateTime(now);

            // 下单限购
            tbActivePo.setLimitBuyNum(activeUpdateDto.getLimitBuyNum());
            tbActivePo.setLimitEnrollNum(activeUpdateDto.getLimitBuyNum());
            // 隐藏链接
            tbActivePo.setHideLink(activeUpdateDto.getHideLink());
            // 过期自动退款
            tbActivePo.setAutoRefundEnabled(activeUpdateDto.getAutoRefundEnabled());
            // 更新库存
            if (ActiveStateEnum.NO_START.getValue().equals(activeState)) {
                updateActiveGoodsStock(activeUpdateDto, tbActivePo);
            }

            int count = baseMapper.updateById(tbActivePo);
            if (count == 0) {
                Throw.isBusinessException("修改活动失败");
            }

            // 拼团配置
            GroupBuyActiveReleaseDto groupBuyUpdateDto = BeanUtil.copyProperties(activeUpdateDto, GroupBuyActiveReleaseDto.class);
            activeGroupBuyService.saveGroupBuyActive(groupBuyUpdateDto);

            return true;
        }

        return true;
    }

    private void updateActiveGoodsStock(ActiveUpdateDto activeUpdateDto, TbActivePo tbActivePo) {
        // 更新库存
        if (activeUpdateDto.getTotalStock() != null
                && !activeUpdateDto.getTotalStock().equals(tbActivePo.getTotalStock())) {
            List<ActiveGoodsSonDto> activeGoodsList = activeGoodsMapper.listByActiveId(activeUpdateDto.getId());

            // 已卖出 = total_stock - remain_stock
            int soldStock = tbActivePo.getTotalStock() - tbActivePo.getRemainStock();
            if (activeUpdateDto.getTotalStock() < soldStock) {
                Throw.isBusinessException("库存不能低于已售出的数量：" + soldStock);
            }

            // 变更后的库存差值
            int totalStockDiff = activeUpdateDto.getTotalStock() - tbActivePo.getTotalStock();

            for (ActiveGoodsSonDto activeGood : activeGoodsList) {
                Integer goodsNum = activeGood.getGoodsNum();
                Integer mulState = activeGood.getMulState();

                if (MulStateEnum.YES.getValue().equals(mulState)) {
                    continue;
                }

                int subTotalStock = goodsNum * totalStockDiff;

                // 扣除商品的库存
                int count = goodsMapper.subStock(Long.parseLong(activeGood.getGoodsId()), subTotalStock);
                if (count == 0) {
                    log.error("添加活动失败，扣减商品库存异常");
                    Throw.isBusinessException("商品【" + activeGood.getGoodsName() + "】库存不足");
                }

                count = activeGoodsStockMapper.subFreezeStock(tbActivePo.getId(), activeGood.getGoodsId(), subTotalStock * -1);
                if (count == 0) {
                    log.error("更新活动失败，保存商品活动库存数据异常");
                    Throw.isBusinessException("更新活动失败");
                }
            }
            // 活动库存
            int res = baseMapper.addTotalAndRemainStock(tbActivePo.getId(), totalStockDiff);
            if (res == 0) {
                log.error("更新活动失败，保存商品活动库存数据异常");
                Throw.isBusinessException("更新活动失败");
            }
        }
    }

    @Override
    public AppMyActiveDetailsVo myActiveDetails(Long id) {
        TbActivePo tbActivePo = baseMapper.selectById(id);
        if (tbActivePo == null || tbActivePo.getDelState() != 0) {
            Throw.isBusinessException("未找到活动数据");
        }

        AppMyActiveDetailsVo appMyActiveDetailsVo = new AppMyActiveDetailsVo();
        BeanUtils.copyProperties(tbActivePo, appMyActiveDetailsVo);

        // 设置活动标签
        appMyActiveDetailsVo.setLabels(activeLabelService.getActiveLabels(id));

        LocalDateTime now = LocalDateTime.now();

        // 对未开始和进行中的活动状态处理
        Integer activeState = appMyActiveDetailsVo.getActiveState();
        if (ActiveStateEnum.NO_START.getValue().equals(activeState) || ActiveStateEnum.IN_PROGRESS.getValue().equals(activeState)) {
            LocalDateTime startTime = appMyActiveDetailsVo.getStartTime();
            LocalDateTime endTime = appMyActiveDetailsVo.getEndTime();

            if (startTime.compareTo(now) > 0) {
                appMyActiveDetailsVo.setActiveState(ActiveStateEnum.NO_START.getValue());
            } else if (endTime.compareTo(now) <= 0) {
                appMyActiveDetailsVo.setActiveState(ActiveStateEnum.ENDED.getValue());
            } else if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
                appMyActiveDetailsVo.setActiveState(ActiveStateEnum.IN_PROGRESS.getValue());
            }
        }

        Integer activeType = tbActivePo.getActiveType();
        if (ActiveTypeEnum.GROUP.getValue().equals(activeType)) {
            setActiveGroupInfo(id, tbActivePo, appMyActiveDetailsVo);
        } else if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
            setEnrollInfo(id, tbActivePo, appMyActiveDetailsVo);
        } else if (ActiveTypeEnum.GROUP_ENROLL.getValue().equals(activeType)) {
            setActiveGroupInfo(id, tbActivePo, appMyActiveDetailsVo);
            setEnrollInfo(id, tbActivePo, appMyActiveDetailsVo);
        } else {
            return appMyActiveDetailsVo;
        }

        // 是否是所有经纪人可推广：1-是，2-否
        Integer agentNumState = tbActivePo.getAgentNumState();
        if (AgentNumStateEnum.NO.getValue().equals(agentNumState)) {
            // 分销经纪人列表
            appMyActiveDetailsVo.setAgentIds(activeAgentMapper.listByActiveId(id));
        }

        // 新人首单红包
        List<ActiveRedPacketSonDto> activeRedPackets = activeRedPacketMapper.listByActiveIds(Collections.singletonList(id));
        if (!CollectionUtils.isEmpty(activeRedPackets)) {
            appMyActiveDetailsVo.setActiveRedPacket(activeRedPackets.get(0));
        }

        // 拼团设置
        if (PromotionTypeEnum.GROUP_BUY.name().equals(appMyActiveDetailsVo.getPromotionType())) {
            TbActiveGroupBuyPo activeGroupBuyPo = activeGroupBuyService.getByActiveId(appMyActiveDetailsVo.getId());
            appMyActiveDetailsVo.setActiveGroupBuy(BeanUtil.copyProperties(activeGroupBuyPo, ActiveGroupBuyVo.class));
        }

        return appMyActiveDetailsVo;
    }

    private void setEnrollInfo(Long id, TbActivePo tbActivePo, AppMyActiveDetailsVo appMyActiveDetailsVo) {
        // 阶梯价格列表
        if (StepPriceStateEnum.YES.getValue().equals(tbActivePo.getStepPriceState())) {
            List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceMapper.listByActiveIds(Collections.singletonList(id));
            appMyActiveDetailsVo.setActiveStepPrices(activeStepPriceSonDtoList);

            // 将阶梯价格的最高价设置为活动价格显示
//            appMyActiveDetailsVo.setActivePrice(getMaxStepPrice(activeStepPriceSonDtoList));
        }

        // 报名信息列表
        List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeEnrollInfoMapper.listByActiveId(id);
        // 对单选项数据处理
        if (!CollectionUtils.isEmpty(activeEnrollInfos)) {
            for (ActiveEnrollInfoSonDto activeEnrollInfo : activeEnrollInfos) {
                if (ActiveEnrollInfoTypeEnum.WRITE.getValue().equals(activeEnrollInfo.getType())) {
                    continue;
                }

                String content = activeEnrollInfo.getContent();
                if (StringUtils.isEmpty(content)) {
                    continue;
                }

                activeEnrollInfo.setActiveEnrollInfoOptions(JSON.parseArray(content, ActiveEnrollInfoOptionDto.class));
                activeEnrollInfo.setContent("");
            }

            activeEnrollInfos = activeEnrollInfos.stream()
                    .peek(e -> {
                        if (e.getSort() == null) {
                            e.setSort(1);
                        }
                    })
                    .sorted(Comparator.comparing(ActiveEnrollInfoSonDto::getSort))
                    .collect(Collectors.toList());
        }

        appMyActiveDetailsVo.setActiveEnrollInfos(activeEnrollInfos);
    }

    private void setActiveGroupInfo(Long id, TbActivePo tbActivePo, AppMyActiveDetailsVo appMyActiveDetailsVo) {
        // 活动商品列表
        appMyActiveDetailsVo.setActiveGoods(activeGoodsMapper.listByActiveId(id));

        // 活动商品补贴列表
        if (SubsidyStateEnum.MANUAL.getValue().equals(tbActivePo.getSubsidyState())) {
            appMyActiveDetailsVo.setActiveGoodsSubsidy(activeGoodsSubsidyMapper.listByActiveId(id));
        }

        // 多件多折列表
        if (DiscountStateEnum.OPEN.getValue().equals(tbActivePo.getDiscountState())) {
            appMyActiveDetailsVo.setActiveDiscount(activeDiscountMapper.listByActiveIds(Collections.singletonList(id)));
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void adminDelete(Long id) {
        TbActivePo tbActivePo = baseMapper.selectById(id);
        if (tbActivePo == null || tbActivePo.getDelState() != 0) {
            Throw.isBusinessException("未找到活动数据");
        }

        if (tbActivePo.getActiveState().equals(ActiveStateEnum.IN_PROGRESS.getValue())) {
            Throw.isBusinessException("活动进行中无法删除");
        }

        if (tbActivePo.getStartTime().isBefore(LocalDateTime.now()) && tbActivePo.getEndTime().isAfter(LocalDateTime.now())) {
            Throw.isBusinessException("活动进行中无法删除");
        }

        tbActivePo.setDelState(1);
        tbActivePo.setUpdateTime(LocalDateTime.now());
        int count = baseMapper.updateById(tbActivePo);
        if (count == 0) {
            Throw.isBusinessException("删除活动数据失败");
        }
        // 释放库存
        if (ActiveTypeEnum.GROUP.getValue().equals(tbActivePo.getActiveType())
                || ActiveTypeEnum.GROUP_ENROLL.getValue().equals(tbActivePo.getActiveType())) {
            List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.selectList(new QueryWrapper<TbActiveGoodsStockPo>()
                    .eq("active_id", tbActivePo.getId()));
            if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
                for (TbActiveGoodsStockPo activeGoodsStockPo : activeGoodsStockPos) {
                    Long goodsId = activeGoodsStockPo.getGoodsId();
                    Integer freezeStock = activeGoodsStockPo.getFreezeStock();

                    if (freezeStock > 0) {
                        goodsMapper.addStock(goodsId, freezeStock);

                        activeGoodsStockPo.setFreezeStock(0);
                        activeGoodsStockPo.setUpdateTime(LocalDateTime.now());
                        activeGoodsStockMapper.updateById(activeGoodsStockPo);
                    }
                }
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteActive(Long id, Long userId, Long businessId) {
        TbActivePo tbActivePo = baseMapper.selectById(id);
        if (tbActivePo == null || tbActivePo.getDelState() != 0) {
            Throw.isBusinessException("未找到活动数据");
        }

        checkActiveOperationPermission(userId, businessId, tbActivePo);

        tbActivePo.setDelState(1);
        tbActivePo.setUpdateTime(LocalDateTime.now());
        int count = baseMapper.updateById(tbActivePo);
        if (count == 0) {
            Throw.isBusinessException("删除活动数据失败");
        }

        // 释放库存
        if (ActiveTypeEnum.GROUP.getValue().equals(tbActivePo.getActiveType())
                || ActiveTypeEnum.GROUP_ENROLL.getValue().equals(tbActivePo.getActiveType())) {
            List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.selectList(new QueryWrapper<TbActiveGoodsStockPo>()
                    .eq("active_id", tbActivePo.getId()));
            if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
                for (TbActiveGoodsStockPo activeGoodsStockPo : activeGoodsStockPos) {
                    Long goodsId = activeGoodsStockPo.getGoodsId();
                    Integer freezeStock = activeGoodsStockPo.getFreezeStock();

                    if (freezeStock > 0) {
                        goodsMapper.addStock(goodsId, freezeStock);

                        activeGoodsStockPo.setFreezeStock(0);
                        activeGoodsStockPo.setUpdateTime(LocalDateTime.now());
                        activeGoodsStockMapper.updateById(activeGoodsStockPo);
                    }
                }
            }
        }
        return true;
    }

    private void checkActiveOperationPermission(Long userId, Long businessId, TbActivePo tbActivePo) {
        if (businessId == null || businessId <= 0) {
            if (userId == null || userId <= 0) {
                Throw.isBusinessException(ResponseEnums.USER_ACCESS_DENIED);
            }

            BusinessPageVo businessPageVo = businessApi.getByUserId(userId).unpack();
            if (businessPageVo == null) {
                Throw.isBusinessException(ResponseEnums.BUSINESS_ACCESS_DENIED);
            }

            businessId = businessPageVo.getId();
        }

        if (!tbActivePo.getBusinessId().equals(businessId)) {
            log.error("删除活动，没有操作权限，businessId：{}，activeBusinessId：{}", businessId, tbActivePo.getBusinessId());
            Throw.isBusinessException("没有操作权限");
        }
    }

    @Override
    public boolean takeDownActive(Long id, Long userId, Long businessId) {
        TbActivePo tbActivePo = Optional.ofNullable(baseMapper.selectById(id))
                .orElseThrow(() -> new BusinessException("未找到活动数据"));

        checkActiveOperationPermission(userId, businessId, tbActivePo);

        // 进行中才能下架
        Integer activeState = tbActivePo.getActiveState();

        if (ActiveStateEnum.ENDED.getValue().equals(activeState)) {
            Throw.isBusinessException("该活动已结束");
        }

        if (!ActiveStateEnum.IN_PROGRESS.getValue().equals(activeState)) {
            // 再次校验一下活动时间，在活动开始-结束时间内的就算是进行中
            LocalDateTime now = LocalDateTime.now();
            if (tbActivePo.getStartTime().isAfter(now) || tbActivePo.getEndTime().isBefore(now)) {
                Throw.isBusinessException("进行中的活动才能下架");
            }
        }

        // 下架即结束活动
        tbActivePo.setActiveState(ActiveStateEnum.ENDED.getValue());
        tbActivePo.setUpdateTime(LocalDateTime.now());
        int count = baseMapper.updateById(tbActivePo);
        if (count == 0) {
            Throw.isBusinessException("下架活动失败");
        }

        // 释放库存
        if (ActiveTypeEnum.GROUP.getValue().equals(tbActivePo.getActiveType())
                || ActiveTypeEnum.GROUP_ENROLL.getValue().equals(tbActivePo.getActiveType())) {
            List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.selectList(new QueryWrapper<TbActiveGoodsStockPo>()
                    .eq("active_id", tbActivePo.getId()));
            if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
                for (TbActiveGoodsStockPo activeGoodsStockPo : activeGoodsStockPos) {
                    Long goodsId = activeGoodsStockPo.getGoodsId();
                    Integer freezeStock = activeGoodsStockPo.getFreezeStock();

                    if (freezeStock > 0) {
                        goodsMapper.addStock(goodsId, freezeStock);

                        activeGoodsStockPo.setFreezeStock(0);
                        activeGoodsStockPo.setUpdateTime(LocalDateTime.now());
                        activeGoodsStockMapper.updateById(activeGoodsStockPo);
                    }
                }
            }
        }

        return true;
    }

    @Override
    public Page<IndexActivePageVo> pageIndexActive(IndexActivePageDto indexActivePageDto) {
        LocalDateTime now = LocalDateTime.now();
        String nowStr = LocalDateUtil.toLocalDateTimeToString(now, Constant.YYYY_MM_DD_HH_MM_SS);
//        Integer type = indexActivePageDto.getType();
//        if (type == 2) {
//            // 推荐:根据定位返回对应的近一个月进行中的活动列表，按销量降序
//            LocalDateTime localDateTime = now.plusMonths(-1);
//
//            indexActivePageDto.setReleaseTimeStart(LocalDateUtil.toLocalDateTimeToString(localDateTime, Constant.YYYY_MM_DD_HH_MM_SS));
//            indexActivePageDto.setReleaseTimeEnd(nowStr);
//        }

        indexActivePageDto.setActiveStates(Arrays.asList(ActiveStateEnum.NO_START.getValue(), ActiveStateEnum.IN_PROGRESS.getValue()));
        indexActivePageDto.setNowTime(nowStr);
        PageHelper.startPage(indexActivePageDto.getPageNum(), indexActivePageDto.getPageSize());
        List<IndexActivePageVo> indexActiveList = baseMapper.listIndexActiveByDto(indexActivePageDto);
        if (!CollectionUtils.isEmpty(indexActiveList)) {
            List<Long> activeIds = indexActiveList.stream().map(IndexActivePageVo::getId).collect(Collectors.toList());
            List<Long> businessIds = indexActiveList.stream().map(IndexActivePageVo::getBusinessId).distinct().collect(Collectors.toList());
            Long userId = indexActivePageDto.getUserId();
            Long agent1Id = indexActivePageDto.getAgent1Id();
            Long agent2Id = indexActivePageDto.getAgent2Id();
            BigDecimal subAgentCommissionRate = indexActivePageDto.getSubAgentCommissionRate();

            // 查询多件多折列表
            Map<Long, List<ActiveDiscountSonDto>> tbActiveDiscountPoMap = new HashMap<>();
            List<ActiveDiscountSonDto> tbActiveDiscountPos = activeDiscountMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(tbActiveDiscountPos)) {
                tbActiveDiscountPoMap = tbActiveDiscountPos.stream().collect(Collectors.groupingBy(ActiveDiscountSonDto::getActiveId));
            }

            // 查询新人首单红包数据
            Map<Long, ActiveRedPacketSonDto> activeRedPacketSonDtoMap = new HashMap<>();
            List<ActiveRedPacketSonDto> activeRedPacketSonDtoList = activeRedPacketMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeRedPacketSonDtoList)) {
                activeRedPacketSonDtoMap = activeRedPacketSonDtoList.stream().collect(Collectors.toMap(ActiveRedPacketSonDto::getActiveId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询阶梯价格列表
            Map<Long, List<ActiveStepPriceSonDto>> activeStepPriceSonDtoMap = new HashMap<>();
            List<ActiveStepPriceSonDto> activeStepPriceSonDtos = activeStepPriceMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeStepPriceSonDtos)) {
                activeStepPriceSonDtoMap = activeStepPriceSonDtos.stream().collect(Collectors.groupingBy(ActiveStepPriceSonDto::getActiveId));
            }

            // 用户订阅的商家id列表
            List<Long> subscribeBusinessIds = new ArrayList<>();
            if (userId != null && userId > 0) {
                subscribeBusinessIds = businessSubscribeApi.listByUserId(userId).unpack();
            }

            // 分销经纪人列表（根据活动的商家id批量查询活动经纪人关联表）
            Map<Long, List<TbActiveAgentPo>> activeAgentMap = new HashMap<>();
            List<TbActiveAgentPo> activeAgentPos = activeAgentMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeAgentPos)) {
                activeAgentMap = activeAgentPos.stream().collect(Collectors.groupingBy(TbActiveAgentPo::getActiveId));
            }

            // 查询商家经纪人关联数据
            Map<Long, List<BusinessAgentVo>> businessAgentVoMap = new HashMap<>();
            List<BusinessAgentVo> businessAgentVos = businessAgentApi.listByBusinessIds(businessIds).unpack();
            if (!CollectionUtils.isEmpty(businessAgentVos)) {
                businessAgentVoMap = businessAgentVos.stream().collect(Collectors.groupingBy(BusinessAgentVo::getBusinessId));
            }

            // 查询商家数据
            Map<Long, BusinessVo> businessVoMap = new HashMap<>();
            List<BusinessVo> businessVos = businessApi.listByIds(businessIds).unpack();
            if (!CollectionUtils.isEmpty(businessVos)) {
                businessVoMap = businessVos.stream().collect(Collectors.toMap(BusinessVo::getId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询活动浏览数
            Map<Long, List<TbActiveBrowseStatisticsPo>> tbActiveBrowseStatisticsPoMap = new HashMap<>();
            List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPos = activeBrowseStatisticsMapper.selectList(new QueryWrapper<TbActiveBrowseStatisticsPo>()
                    .eq("del_state", 0)
                    .in("active_id", activeIds));
            if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPos)) {
                tbActiveBrowseStatisticsPoMap = tbActiveBrowseStatisticsPos.stream().collect(Collectors.groupingBy(TbActiveBrowseStatisticsPo::getActiveId));
            }

            Map<Long, List<Long>> userBrowseMap = new HashMap<>();
            Map<Long, AppUserVo> activeBrowseAppUserVoMap = new HashMap<>();
            List<TbActiveBrowsePo> activeBrowsePos = activeBrowseMapper.selectList(new QueryWrapper<TbActiveBrowsePo>().eq("del_state", 0)
                    .in("active_id", activeIds));
            if (!CollectionUtils.isEmpty(activeBrowsePos)) {
                Map<Long, List<TbActiveBrowsePo>> activeBrowseMap = activeBrowsePos.stream().collect(Collectors.groupingBy(TbActiveBrowsePo::getActiveId));

                Set<Long> userIdAllSet = new HashSet<>();
                for (Long activeId : activeBrowseMap.keySet()) {
                    List<TbActiveBrowsePo> activeBrowsePoList = activeBrowseMap.get(activeId);
                    if (CollectionUtils.isEmpty(activeBrowsePoList)) {
                        continue;
                    }

                    List<Long> userIds;
                    Set<Long> userIdSet = activeBrowsePoList.stream().map(TbActiveBrowsePo::getUserId).collect(Collectors.toSet());
                    if (userIdSet.size() > 3) {
                        userIds = new ArrayList<>(userIdSet).subList(0, 3);
                    } else {
                        userIds = new ArrayList<>(userIdSet);
                    }

                    if (!CollectionUtils.isEmpty(userIds)) {
                        userBrowseMap.put(activeId, userIds);
                        userIdAllSet.addAll(userIds);
                    }
                }

                if (!CollectionUtils.isEmpty(userIdAllSet)) {
                    List<Long> userIds = new ArrayList<>(userIdAllSet);
                    List<AppUserVo> appUserVos = appUserApi.listByUserIds(userIds).unpack();
                    if (!CollectionUtils.isEmpty(appUserVos)) {
                        activeBrowseAppUserVoMap = appUserVos.stream().collect(Collectors.toMap(AppUserVo::getId, Function.identity(), (k1, k2) -> k2));
                    }
                }
            }

            // 查询收藏的活动的下单用户列表
            Map<Long, List<OrderVo>> orderVoMap = new HashMap<>();
            OrderDto orderDto = new OrderDto();
            orderDto.setActiveIds(activeIds);
            orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_VERIFY.getValue(),
                    OrderStateEnum.VERIFYING.getValue(),
                    OrderStateEnum.FINISH.getValue(),
                    OrderStateEnum.VERIFIED.getValue()));
            List<OrderVo> orderVos = orderApi.listByDto(orderDto).unpack();
            if (!CollectionUtils.isEmpty(orderVos)) {
                orderVoMap = orderVos.stream().collect(Collectors.groupingBy(OrderVo::getActiveId));
            }

            Map<Long, BigDecimal> agentCommissionRate = new HashMap<>();
            // 如果是经纪人，那就获取经纪人跟商家的佣金比例
            if (agent1Id != null && agent1Id > 0) {
                agentCommissionRate = businessAgentApi.getAgentCommissionRateByBusinessIds(agent1Id, businessIds).unpack();
            }

            // 经纪人分享次数
            List<ActiveAgentShareCountVo> activeAgentShareCountVos = activeShareMapper.getAgentShareCountByActiveIds(activeIds);
            Map<Long, Integer> agentShareCount = activeAgentShareCountVos.stream()
                    .collect(Collectors.toMap(
                            ActiveAgentShareCountVo::getActiveId, // 使用getActiveId作为Map的key
                            ActiveAgentShareCountVo::getAgentShareCount // 使用getAgentShareCount作为Map的value
                    ));

            // 判断用户是否分享过该活动
            List<Long> userSharedActiveIds = Collections.emptyList();
            if (userId != null && userId > 0) {
                userSharedActiveIds = activeShareMapper.getUserShareActiveIds(userId, activeIds);
            }

            for (IndexActivePageVo indexActivePageVo : indexActiveList) {
                Long id = indexActivePageVo.getId();
                Long businessId = indexActivePageVo.getBusinessId();
                // 是否是所有经纪人可推广：1-是，2-否
                Integer agentNumState = indexActivePageVo.getAgentNumState();

                List<ActiveDiscountSonDto> activeDiscountSonDtos = tbActiveDiscountPoMap.get(id);
                if (!CollectionUtils.isEmpty(activeDiscountSonDtos)) {
                    indexActivePageVo.setActiveDiscount(activeDiscountSonDtos);
                }

                ActiveRedPacketSonDto activeRedPacketSonDto = activeRedPacketSonDtoMap.get(id);
                if (activeRedPacketSonDto != null) {
                    indexActivePageVo.setActiveRedPacket(activeRedPacketSonDto);
                }

                List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceSonDtoMap.get(id);
                if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
                    indexActivePageVo.setActiveStepPrices(activeStepPriceSonDtoList);

                    // 将阶梯价格的最高价设置为活动价格显示
//                    indexActivePageVo.setActivePrice(getMaxStepPrice(activeStepPriceSonDtoList));
                }

                // 经纪人分享次数
                Integer shareCount = agentShareCount.get(id);
                if (shareCount != null && shareCount > 0) {
                    indexActivePageVo.setAgentShareCount(shareCount);
                }

                // 订阅状态：1-未订阅，2-已订阅
                if (userId != null && userId > 0) {
                    if (!CollectionUtils.isEmpty(subscribeBusinessIds) && subscribeBusinessIds.contains(businessId)) {
                        indexActivePageVo.setSubscribeState(SubscribeBusinessStateEnum.YES.getValue());
                    }

                    // 判断是否是商家经济人，是的话才能推广
                    Optional<List<BusinessAgentVo>> businessAgentVoListOpt = Optional.ofNullable(businessAgentVoMap.get(businessId));
                    boolean haveAgent = businessAgentVoListOpt.map(list -> list.stream()
                                    .collect(Collectors.toMap(BusinessAgentVo::getUserId, Function.identity(), (k1, k2) -> k2))
                                    .containsKey(agent1Id))
                            .orElse(false);
                    // 如果不是商家的所有经纪人可推广，则判断当前用户是否是该活动所关联的经纪人
                    if (haveAgent && AgentNumStateEnum.NO.getValue().equals(agentNumState)) {
                        Optional<List<TbActiveAgentPo>> activeAgentPoListOpt = Optional.ofNullable(activeAgentMap.get(id));
                        haveAgent = activeAgentPoListOpt.map(list -> list.stream()
                                        .collect(Collectors.toMap(TbActiveAgentPo::getAgentId, Function.identity(), (k1, k2) -> k2))
                                        .containsKey(agent1Id))
                                .orElse(false);
                    }
                    // 是否具备分销权限
                    indexActivePageVo.setHaveAgent(haveAgent);
                }

//                BigDecimal actualCommissionAmt = Optional.ofNullable(indexActivePageVo.getCommissionAmt()).orElse(BigDecimal.ZERO);
                BigDecimal actualCommissionRate = Optional.ofNullable(indexActivePageVo.getCommissionRate()).orElse(BigDecimal.ZERO);
                BigDecimal actualCommissionAmt = indexActivePageVo.getActivePrice().multiply(actualCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);

                indexActivePageVo.setCommissionAmt(BigDecimal.ZERO);
                indexActivePageVo.setCommissionRate(BigDecimal.ZERO);

                // 能分销，才设置佣金比例
                if (indexActivePageVo.getHaveAgent()
                        && AgentStateEnum.OPEN.getValue().equals(indexActivePageVo.getAgentState())) {
                    // 是否分享过该活动: 0未推广 1已推广
                    if (!CollectionUtils.isEmpty(userSharedActiveIds) && userSharedActiveIds.contains(indexActivePageVo.getId())) {
                        indexActivePageVo.setAgentShareState(1);
                    }


                    BigDecimal exclusiveCommissionRate = agentCommissionRate.getOrDefault(businessId, BigDecimal.valueOf(-1));
                    // 如果有设置专属佣金比例或者分组佣金比例，就按照这个比例来计算佣金
                    if (exclusiveCommissionRate != null && exclusiveCommissionRate.compareTo(BigDecimal.ZERO) > 0) {
                        actualCommissionRate = exclusiveCommissionRate;
                        actualCommissionAmt = indexActivePageVo.getActivePrice().multiply(actualCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP);
                        indexActivePageVo.setDefaultCommissionType(DefaultCommissionTypeEnum.COMMISSION_RATE.getValue());
                    }
                    if (indexActivePageVo.getDefaultCommissionType().equals(DefaultCommissionTypeEnum.NULL.getValue())) {
                        actualCommissionAmt = BigDecimal.ZERO;
                        actualCommissionRate = BigDecimal.ZERO;
                    }
                    // 二级经纪人佣金比例
                    if (agent2Id != null && agent2Id > 0) {
                        if (subAgentCommissionRate == null || subAgentCommissionRate.compareTo(BigDecimal.ZERO) <= 0) {
                            actualCommissionAmt = BigDecimal.ZERO;
                            actualCommissionRate = BigDecimal.ZERO;
                        } else {
                            actualCommissionRate = actualCommissionRate.multiply(subAgentCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
                            actualCommissionAmt = actualCommissionAmt.multiply(subAgentCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
                        }
                    }
                    indexActivePageVo.setCommissionAmt(actualCommissionAmt);
                    indexActivePageVo.setCommissionRate(actualCommissionRate);

                    if (indexActivePageVo.getRewardType().equals(RewardTypeEnum.POINTS.getValue())) {
                        if (agent2Id != null && agent2Id > 0) {
                            BigDecimal agentPointsAmt = Optional.ofNullable(indexActivePageVo.getRewardPoints()).orElse(BigDecimal.ZERO);
                            BigDecimal subAgentPointsAmt = subAgentCommissionRate.multiply(agentPointsAmt).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
                            indexActivePageVo.setRewardPoints(subAgentPointsAmt);
                        }
                    }
                }

                BusinessVo businessVo = businessVoMap.get(businessId);
                if (businessVo != null) {
                    indexActivePageVo.setBusinessName(businessVo.getBusinessName());
                    indexActivePageVo.setBusinessShortName(businessVo.getBusinessShortName());
                    indexActivePageVo.setLogo(businessVo.getLogo());
                }

                List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPoList = tbActiveBrowseStatisticsPoMap.get(id);
                if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPoList)) {
                    indexActivePageVo.setBrowseNum(tbActiveBrowseStatisticsPoList.stream().mapToLong(TbActiveBrowseStatisticsPo::getBrowseNum).sum());
                }

                int buyNum = 0;
                List<OrderVo> orderVoList = orderVoMap.get(id);
                if (!CollectionUtils.isEmpty(orderVoList)) {
                    buyNum = orderVoList.stream().mapToInt(OrderVo::getOrderNum).sum();
                }
                indexActivePageVo.setBuyNum(buyNum + indexActivePageVo.getSaleNum());

                List<String> avatars = new ArrayList<>();
                List<Long> userIds = userBrowseMap.get(id);
                if (!CollectionUtils.isEmpty(userIds)) {
                    for (Long uid : userIds) {
                        AppUserVo appUserVo = activeBrowseAppUserVoMap.get(uid);
                        if (appUserVo != null) {
                            avatars.add(appUserVo.getAvatar());
                        }
                    }
                }

                indexActivePageVo.setAvatars(avatars);
            }

            // 拼团活动标识
            processActivesGroupBuyTag(indexActiveList);
        }

        PageInfo<IndexActivePageVo> pageInfo = new PageInfo<>(indexActiveList);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    private void processActivesGroupBuyTag(List<IndexActivePageVo> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        List<Long> activeIds = dataList.stream()
                .filter(e -> PromotionTypeEnum.GROUP_BUY.name().equals(e.getPromotionType()))
                .map(IndexActivePageVo::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activeIds)) {
            return;
        }
        Map<Long, TbActiveGroupBuyPo> activeIdToGroupBuyInfo = activeGroupBuyService.listByActiveIds(activeIds)
                .stream()
                .collect(Collectors.toMap(TbActiveGroupBuyPo::getActiveId, Function.identity()));
        for (IndexActivePageVo indexActivePageVo : dataList) {
            TbActiveGroupBuyPo groupBuyInfo = activeIdToGroupBuyInfo.get(indexActivePageVo.getId());
            if (groupBuyInfo != null) {
                indexActivePageVo.setPromotionLabel(groupBuyInfo.getGroupNum() + "人团");
                indexActivePageVo.setActivePrice(groupBuyInfo.getGroupBuyPrice());
            }
        }
    }

    @Override
    public ActiveDetailsVo details(Long id, Long userId, String shareCode) {
        TbActivePo tbActivePo = baseMapper.selectById(id);
        if (tbActivePo == null || tbActivePo.getDelState() != 0) {
            Throw.isBusinessException(ResponseEnums.ACTIVE_DOWN);
        }

        ActiveDetailsVo activeDetailsVo = new ActiveDetailsVo();
        BeanUtils.copyProperties(tbActivePo, activeDetailsVo);

        // 拼团标识
        if (PromotionTypeEnum.GROUP_BUY.name().equals(tbActivePo.getPromotionType())) {
            TbActiveGroupBuyPo groupBuyInfo = activeGroupBuyService.getByActiveId(id);
            ActiveGroupBuyVo activeGroupBuyVo = BeanUtil.copyProperties(groupBuyInfo, ActiveGroupBuyVo.class);
            // 开团权限
            Boolean hasCreateGroupPermission = activeGroupBuyService.hasCreateGroupPermission(activeGroupBuyVo.getActiveId(), userId);
            activeGroupBuyVo.setHasCreateGroupPermission(hasCreateGroupPermission);
            activeDetailsVo.setActiveGroupBuy(activeGroupBuyVo);

            if (groupBuyInfo != null) {
                activeDetailsVo.setPromotionLabel(groupBuyInfo.getGroupNum() + "人团");
                activeDetailsVo.setLeadFreeEnabled(groupBuyInfo.getLeadFreeEnabled());
            }
        }

        Long businessId = tbActivePo.getBusinessId();
        // 根据活动时间处理活动状态
        Integer activeState = tbActivePo.getActiveState();
        LocalDateTime now = LocalDateTime.now();

        if (!ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)
                && !ActiveStateEnum.ENDED.getValue().equals(activeState)) {
            LocalDateTime startTime = tbActivePo.getStartTime();
            LocalDateTime endTime = tbActivePo.getEndTime();
            if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
                activeState = ActiveStateEnum.IN_PROGRESS.getValue();
            } else if (endTime.compareTo(now) <= 0) {
                activeState = ActiveStateEnum.ENDED.getValue();
            } else if (startTime.compareTo(now) > 0) {
                activeState = ActiveStateEnum.NO_START.getValue();
            }
        }

        activeDetailsVo.setActiveState(activeState);

        if (userId != null && userId > 0) {
            // 查询收藏记录表
            Integer count = activeCollectMapper.selectCount(new QueryWrapper<TbActiveCollectPo>().eq("del_state", 0)
                    .eq("active_id", id).eq("user_id", userId));
            activeDetailsVo.setCollectState((count != null && count > 0)
                    ? ActiveCollectStateEnum.YES.getValue() : ActiveCollectStateEnum.NO.getValue());

            List<Long> subscribeBusinessIds = businessSubscribeApi.listByUserId(userId).unpack();
            // 订阅状态：1-未订阅，2-已订阅
            activeDetailsVo.setSubscribeState((!CollectionUtils.isEmpty(subscribeBusinessIds) && subscribeBusinessIds.contains(businessId))
                    ? SubscribeBusinessStateEnum.YES.getValue() : SubscribeBusinessStateEnum.NO.getValue());

            // 如果是未发布/未开始的活动，不存浏览记录
            if (!ActiveStateEnum.NO_RELEASE.getValue().equals(activeState) && !ActiveStateEnum.NO_START.getValue().equals(activeState)) {
                // 发送mq消息异步处理活动浏览记录
                ActiveBrowseMsg activeBrowseMsg = new ActiveBrowseMsg();
                activeBrowseMsg.setBusinessId(businessId);
                activeBrowseMsg.setActiveId(id);
                activeBrowseMsg.setUserId(userId);
                activeBrowseMsg.setBrowseTime(now);
                activeBrowseMsgProvider.sendMsg(activeBrowseMsg);
            }

            // 记录用户-商家关联表，这样子用户就可以看到该商家所有的活动
            userBusinessApi.related(userId, businessId);

            // 分销开启状态(1-关闭，2-开启)
            if (AgentStateEnum.OPEN.getValue().equals(tbActivePo.getAgentState())) {
                ActiveShareRewardDto activeShareRewardDto = new ActiveShareRewardDto();
                activeShareRewardDto.setActiveDetailsVo(activeDetailsVo);
                activeShareRewardDto.setShareCode(shareCode);
                activeShareRewardDto.setLoginUserId(userId);
                activeShareRewardProcessor.process(activeShareRewardDto);
//                initAgentData(userId, activeDetailsVo, tbActivePo);
            }
        }

        // 商家信息
        List<BusinessVo> businessVos = businessApi.listByIds(Collections.singletonList(businessId)).unpack();
        if (!CollectionUtils.isEmpty(businessVos)) {
            BusinessVo businessVo = businessVos.get(0);
            activeDetailsVo.setBusinessName(businessVo.getBusinessName());
            activeDetailsVo.setBusinessShortName(businessVo.getBusinessShortName());
            activeDetailsVo.setLogo(businessVo.getLogo());
        }

        // 查询活动浏览数
        List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPos = activeBrowseStatisticsMapper.selectList(new QueryWrapper<TbActiveBrowseStatisticsPo>()
                .eq("del_state", 0)
                .eq("active_id", id));
        activeDetailsVo.setBrowseNum(CollectionUtils.isEmpty(tbActiveBrowseStatisticsPos) ? 0L : tbActiveBrowseStatisticsPos.stream().mapToLong(TbActiveBrowseStatisticsPo::getBrowseNum).sum());

        // 查询活动的下单用户列表
        int buyNum = 0;
        OrderDto orderDto = new OrderDto();
        orderDto.setActiveIds(Collections.singletonList(id));
        orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_VERIFY.getValue(),
                OrderStateEnum.VERIFYING.getValue(),
                OrderStateEnum.FINISH.getValue(),
                OrderStateEnum.VERIFIED.getValue()));
        List<OrderVo> orderVoList = orderApi.listByDto(orderDto).unpack();
        if (!CollectionUtils.isEmpty(orderVoList)) {
            buyNum = orderVoList.stream().mapToInt(OrderVo::getOrderNum).sum();
        }
        activeDetailsVo.setBuyNum(buyNum + activeDetailsVo.getSaleNum());

        // 新人首单红包
        List<ActiveRedPacketSonDto> activeRedPackets = activeRedPacketMapper.listByActiveIds(Collections.singletonList(id));
        if (!CollectionUtils.isEmpty(activeRedPackets)) {
            ActiveRedPacketSonDto activeRedPacketSonDto = activeRedPackets.get(0);
            if (userId != null && userId > 0) {
                // 判断用户是否领取了红包
                List<TbActiveRedPacketBillPo> tbActiveRedPacketBillPos = activeRedPacketBillMapper.selectList(new QueryWrapper<TbActiveRedPacketBillPo>().eq("del_state", 0)
                        .eq("active_id", id).eq("user_id", userId));
                if (!CollectionUtils.isEmpty(tbActiveRedPacketBillPos)) {
                    TbActiveRedPacketBillPo tbActiveRedPacketBillPo = tbActiveRedPacketBillPos.get(0);
                    // 领取红包状态：1-未领取，2-未使用，3-已使用(已过期)，4-已失效
                    activeRedPacketSonDto.setReceiveState(2);
                    if (ActiveRedPacketStateEnum.NO_USE.getValue().equals(tbActiveRedPacketBillPo.getState())) {
                        LocalDateTime expireTime = tbActiveRedPacketBillPo.getExpireTime();
                        if (!now.isBefore(expireTime)) {
                            // 未使用已过期
                            activeRedPacketSonDto.setReceiveState(3);
                        }
                    } else {
                        // 已使用/已过期/已核销
                        activeRedPacketSonDto.setReceiveState(3);
                    }
                }

                // 判断用户是否是该商家的新用户
                orderDto = new OrderDto();
                orderDto.setBusinessId(businessId);
                orderDto.setUserId(userId);
                orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_PAY.getValue(), OrderStateEnum.WAIT_VERIFY.getValue(),
                        OrderStateEnum.VERIFYING.getValue(), OrderStateEnum.FINISH.getValue(), OrderStateEnum.VERIFIED.getValue(),
                        OrderStateEnum.PAYING.getValue()));
                List<OrderVo> orderVos = orderApi.listByDto(orderDto).unpack();
                if (!CollectionUtils.isEmpty(orderVos)) {
                    // 不是商家新用户
                    if (activeRedPacketSonDto.getReceiveState() != 1) {
                        // 如果用户已领取,则返回已失效
                        activeRedPacketSonDto.setReceiveState(4);
                    }
                }
            }

            activeDetailsVo.setActiveRedPacket(activeRedPacketSonDto);
        }

        // 设置用户下单可得积分
        setActiveDetailConsumePoint(activeDetailsVo);

        Integer activeType = tbActivePo.getActiveType();
        if (ActiveTypeEnum.GROUP.getValue().equals(activeType)) {
            setGroupGoodsInfo4ActiveDetailVO(id, tbActivePo, activeDetailsVo);
        } else if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
            setEnrollInfo4ActiveDetailVO(id, tbActivePo, activeDetailsVo);
        } else if (ActiveTypeEnum.GROUP_ENROLL.getValue().equals(activeType)) {
            setGroupGoodsInfo4ActiveDetailVO(id, tbActivePo, activeDetailsVo);
            setEnrollInfo4ActiveDetailVO(id, tbActivePo, activeDetailsVo);
        } else {
            return activeDetailsVo;
        }

        return activeDetailsVo;
    }

    private void setActiveDetailConsumePoint(ActiveDetailsVo activeDetailsVo) {
        Long businessId = activeDetailsVo.getBusinessId();

        // 商家是否有开启积分商城，有的话，用户下单可以拿积分，经纪人分销可以拿积分
        BusinessPageVo businessPageVo = businessApi.getById(businessId).unpack();
        if (businessPageVo == null || !businessPageVo.getPointsMallState().equals(BusinessPointsMallStateEnum.OPEN.getValue())) {
            return;
        }

        BusinessPointsMallSettingsVo businessPointsMallSettingsVo = businessPointsMallApi.getSettings(businessId).unpack();
        if (businessPointsMallSettingsVo == null || businessPointsMallSettingsVo.getConsume() == null) {
            return;
        }
        BigDecimal consumePointsRate = businessPointsMallSettingsVo.getConsume(); // 每消费1元，奖励x积分
        // 下单用户可得积分
        BigDecimal activePrice = activeDetailsVo.getActivePrice();
        if (activeDetailsVo.getActiveGroupBuy() != null) {
            activePrice = activeDetailsVo.getActiveGroupBuy().getGroupBuyPrice();
        }
        BigDecimal userPointsAmt = activePrice.multiply(consumePointsRate);
        activeDetailsVo.setUserPointsAmt(userPointsAmt);
    }

    // 活动可用红包
    @Override
    public List<ActiveRedPacketBilListVo> availableRedPacketList(Long id, Long userId) {
        TbActivePo activePo = baseMapper.selectById(id);
        if (activePo == null) {
            return Collections.emptyList();
        }

        AvailableRedPacketDto dto = new AvailableRedPacketDto();
        dto.setActiveId(id);
        dto.setUserId(userId);
        dto.setBusinessId(activePo.getBusinessId());
        List<ActiveRedPacketBilListVo> listVos = activeRedPacketBillService.activeAvailableList(dto);
        if (listVos == null || listVos.isEmpty()) {
            return Collections.emptyList();
        }

        Integer orderCount = orderApi.userBusinessOrderCount(userId, activePo.getBusinessId()).unpack();
        // 过滤掉新用户红包
        if (orderCount != null && orderCount > 0) {
            listVos = listVos.stream()
                    .filter(vo -> !Objects.equals(vo.getRedPacketType(), RedPacketTypeEnum.NEW_USER.getValue()))
                    .collect(Collectors.toList());
        }
        return listVos;
    }

    private void setEnrollInfo4ActiveDetailVO(Long id, TbActivePo tbActivePo, ActiveDetailsVo activeDetailsVo) {
        // 阶梯价格列表
        if (StepPriceStateEnum.YES.getValue().equals(tbActivePo.getStepPriceState())) {
            List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceMapper.listByActiveIds(Collections.singletonList(id));
            activeDetailsVo.setActiveStepPrices(activeStepPriceSonDtoList);

            // 将阶梯价格的最高价设置为活动价格显示
            BigDecimal maxStepPrice = getMaxStepPrice(activeStepPriceSonDtoList);
            if (activeDetailsVo.getActivePrice().compareTo(BigDecimal.ZERO) == 0
                    && maxStepPrice.compareTo(BigDecimal.ZERO) > 0) {
                activeDetailsVo.setActivePrice(maxStepPrice);
            }
        }

        // 报名信息列表
        List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeEnrollInfoMapper.listByActiveId(id);
        if (!CollectionUtils.isEmpty(activeEnrollInfos)) {
            for (ActiveEnrollInfoSonDto activeEnrollInfo : activeEnrollInfos) {
                if (ActiveEnrollInfoTypeEnum.WRITE.getValue().equals(activeEnrollInfo.getType())) {
                    continue;
                }

                String content = activeEnrollInfo.getContent();
                if (StringUtils.isEmpty(content)) {
                    continue;
                }

                activeEnrollInfo.setActiveEnrollInfoOptions(JSON.parseArray(content, ActiveEnrollInfoOptionDto.class));
                activeEnrollInfo.setContent("");
            }

            // 根据排序值正序
            activeEnrollInfos = activeEnrollInfos.stream().sorted(Comparator.comparing(ActiveEnrollInfoSonDto::getSort)).collect(Collectors.toList());
        }
        activeDetailsVo.setActiveEnrollInfos(activeEnrollInfos);

        // 已报名人数
        int enrolledNum = 0;
        OrderItemDto orderItemDto = new OrderItemDto();
        orderItemDto.setActiveIds(Collections.singletonList(id));
        orderItemDto.setSubOrderStates(
                Arrays.asList(SubOrderStateEnum.WAIT_VERIFY.getValue(),
                        SubOrderStateEnum.VERIFIED.getValue(),
                        SubOrderStateEnum.SETTLED.getValue()));
        orderItemDto.setItemType(OrderItemTypeEnum.SIGN_IN.getValue());
        List<OrderItemVo> tbActiveEnrollOrderItemList = orderItemApi.listByDto(orderItemDto).unpack();
        // 已报名用户列表（返回前6个报名者信息）
        if (!CollectionUtils.isEmpty(tbActiveEnrollOrderItemList)) {
            enrolledNum = tbActiveEnrollOrderItemList.size();
            List<Long> userIds = tbActiveEnrollOrderItemList.stream().map(OrderItemVo::getUserId).collect(Collectors.toList());
            if (userIds.size() > 6) {
                userIds = userIds.subList(0, 6);
            }

            List<AppUserVo> appUserVos = appUserApi.listByUserIds(userIds).unpack();
            if (!CollectionUtils.isEmpty(appUserVos)) {
                activeDetailsVo.setEnrolledAvatars(appUserVos.stream().map(AppUserVo::getAvatar).collect(Collectors.toList()));
            }
        }

        activeDetailsVo.setEnrolledNum(enrolledNum);
    }

    private void setGroupGoodsInfo4ActiveDetailVO(Long id, TbActivePo tbActivePo, ActiveDetailsVo activeDetailsVo) {
        // 活动商品列表
        activeDetailsVo.setActiveGoods(activeGoodsMapper.listByActiveId(id));

        // 活动商品补贴列表
        if (SubsidyStateEnum.MANUAL.getValue().equals(tbActivePo.getSubsidyState())) {
            activeDetailsVo.setActiveGoodsSubsidy(activeGoodsSubsidyMapper.listByActiveId(id));
        }

        // 多件多折列表
        if (DiscountStateEnum.OPEN.getValue().equals(tbActivePo.getDiscountState())) {
            activeDetailsVo.setActiveDiscount(activeDiscountMapper.listByActiveIds(Collections.singletonList(id)));
        }
    }

    // 设置活动经纪人佣金比例
    private void initAgentData(Long userId, ActiveDetailsVo activeDetailsVo, TbActivePo tbActivePo) {
        activeDetailsVo.setHaveAgent(false);

        BigDecimal actualCommissionAmt = Optional.ofNullable(activeDetailsVo.getCommissionAmt()).orElse(BigDecimal.ZERO);
        BigDecimal actualCommissionRate = Optional.ofNullable(activeDetailsVo.getCommissionRate()).orElse(BigDecimal.ZERO);
        activeDetailsVo.setCommissionAmt(BigDecimal.ZERO);
        activeDetailsVo.setCommissionRate(BigDecimal.ZERO);

        BigDecimal activePrice = activeDetailsVo.getActivePrice();
        if (activeDetailsVo.getActiveGroupBuy() != null) {
            activePrice = activeDetailsVo.getActiveGroupBuy().getGroupBuyPrice();
        }

        // 判断是否商家自己查看活动，如果是则佣金展示和一级经纪人一样
        BusinessPageVo business = businessApi.getByUserId(userId).unpack();
        if (business != null && business.getId().equals(tbActivePo.getBusinessId())) {
            if (tbActivePo.getDefaultCommissionType().equals(DefaultCommissionTypeEnum.COMMISSION_RATE.getValue())) {
                actualCommissionAmt = activePrice.multiply(actualCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
                activeDetailsVo.setCommissionAmt(actualCommissionAmt);
                activeDetailsVo.setCommissionRate(actualCommissionRate);
            } else if (tbActivePo.getDefaultCommissionType().equals(DefaultCommissionTypeEnum.COMMISSION.getValue())) {
                activeDetailsVo.setCommissionAmt(actualCommissionAmt);
            }
            return;
        }

        AppUserVo appUserVo = appUserApi.getById(userId).unpack();
        if (appUserVo == null || appUserVo.getAgentState().equals(AgentStateEnum.CLOSE.getValue())) {
            return;
        }

        Long businessId = tbActivePo.getBusinessId();
        Long agent1Id;
        Long agent2Id = 0L;
        if (appUserVo.getAgentId() != null && appUserVo.getAgentId() > 0) {
            agent1Id = appUserVo.getAgentId();
            agent2Id = appUserVo.getId();
        } else {
            agent1Id = appUserVo.getId();
        }

        // 经纪人跟商家的佣金比例, 小于0表示不是绑定关系
        BigDecimal commissionRate = businessAgentApi.getAgentCommissionRate(agent1Id, businessId).unpack();
        if (commissionRate == null || commissionRate.compareTo(BigDecimal.ZERO) < 0) {
            return;
        }

        // 是否是所有经纪人可推广：1-是，2-否
        if (AgentNumStateEnum.NO.getValue().equals(tbActivePo.getAgentNumState())) {
            // 如果不是商家的所有经纪人可推广，则判断当前用户是否是该活动所关联的经纪人
            List<Long> activeAgentList = activeAgentMapper.listByActiveId(tbActivePo.getId());
            if (CollectionUtils.isEmpty(activeAgentList) || !activeAgentList.contains(agent1Id)) {
                return;
            }
        }

        // 如果分组佣金或者专属佣金大于0，就替换掉活动设置的佣金，否则使用活动的佣金
        if (commissionRate.compareTo(BigDecimal.ZERO) > 0) {
            actualCommissionRate = commissionRate;
            actualCommissionAmt = activePrice.multiply(actualCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
            activeDetailsVo.setDefaultCommissionType(DefaultCommissionTypeEnum.COMMISSION_RATE.getValue());
        }

        // 二级经纪人跟一级经纪人的佣金比例
        if (agent2Id != null && agent2Id > 0) {
            BigDecimal rate = businessAgentApi.getSubAgentCommissionRate(agent2Id, agent1Id).unpack();
            if (rate == null || rate.compareTo(BigDecimal.ZERO) <= 0) {
                return;
            }
            actualCommissionRate = actualCommissionRate.multiply(rate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
            actualCommissionAmt = actualCommissionAmt.multiply(rate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
        }

        // 可以分销
        activeDetailsVo.setHaveAgent(true);
        if (activeDetailsVo.getDefaultCommissionType().equals(DefaultCommissionTypeEnum.NULL.getValue())) {
            actualCommissionAmt = BigDecimal.ZERO;
            actualCommissionRate = BigDecimal.ZERO;
        } else if (activeDetailsVo.getDefaultCommissionType().equals(DefaultCommissionTypeEnum.COMMISSION_RATE.getValue())) {
            actualCommissionAmt = activePrice.multiply(actualCommissionRate).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
        }
        activeDetailsVo.setCommissionAmt(actualCommissionAmt);
        activeDetailsVo.setCommissionRate(actualCommissionRate);
    }

    // 活动商品使用说明、可用商户
    private ActiveGoodsUseDetailsVo getActiveGoodsUseDetail(Long activeGoodsId) {
        TbActiveGoodsPo tbActiveGoodsPo = activeGoodsMapper.selectById(activeGoodsId);
        if (tbActiveGoodsPo == null) {
            Throw.isBusinessException("未找到活动商品数据");
        }
        Integer mulState = tbActiveGoodsPo.getMulState();
        String goodsId = tbActiveGoodsPo.getGoodsId();

        ActiveGoodsUseDetailsVo activeGoodsUseDetailsVo = new ActiveGoodsUseDetailsVo();
        if (MulStateEnum.YES.getValue().equals(mulState)) {
            String[] splitGoodsId = goodsId.split(",");
            List<String> merchantIds = Arrays.asList(splitGoodsId);
            // 多商户通用券
            List<MerchantPageVo> merchantVos = merchantApi.listByIds(merchantIds).unpack();
            if (!CollectionUtils.isEmpty(merchantVos)) {
                activeGoodsUseDetailsVo.setMerchantNames(merchantVos.stream().map(MerchantPageVo::getMerchantShortName).collect(Collectors.toList()));
            }

            activeGoodsUseDetailsVo.setDetails(tbActiveGoodsPo.getDetails());
        } else if (MulStateEnum.NO.getValue().equals(mulState)) {
            // 单商户商品券
            TbGoodsPo tbGoodsPo = goodsMapper.selectById(Long.parseLong(goodsId));
            if (tbGoodsPo != null) {
                MerchantVo merchantVo = merchantApi.getById(tbGoodsPo.getMerchantId()).unpack();
                if (merchantVo != null) {
                    activeGoodsUseDetailsVo.setMerchantNames(Collections.singletonList(merchantVo.getMerchantShortName()));
                }
                activeGoodsUseDetailsVo.setDetails(tbGoodsPo.getDetails());
            }
        }

        return activeGoodsUseDetailsVo;
    }

    @Override
    public ActiveGoodsUseDetailsVo useDetails(GoodsUseDetailsDto goodsUseDetailsDto) {
        Long activeGoodsId = goodsUseDetailsDto.getActiveGoodsId();
        Long subOrderId = goodsUseDetailsDto.getSubOrderId();
        if (activeGoodsId != null && activeGoodsId > 0) {
            return getActiveGoodsUseDetail(activeGoodsId);
        }

        OrderItemVo orderItemVo = orderItemApi.getById(subOrderId).unpack();
        if (orderItemVo == null) {
            Throw.isBusinessException("未找到子订单数据");
        }

        activeGoodsId = orderItemVo.getActiveGoodsId();
        if (activeGoodsId != null && activeGoodsId > 0) {
            return getActiveGoodsUseDetail(activeGoodsId);
        }

        ActiveGoodsUseDetailsVo activeGoodsUseDetailsVo = new ActiveGoodsUseDetailsVo();
        // 核销码，积分订单 可用商户
        List<String> merchantIds = new ArrayList<>();
        String goodsId = orderItemVo.getGoodsId();
        if (goodsId != null && !goodsId.isEmpty()) {
            String[] splitGoodsId = orderItemVo.getGoodsId().split(",");
            merchantIds = Arrays.asList(splitGoodsId);
        }
        Long merchantId = orderItemVo.getMerchantId();
        if (merchantId != null && merchantId > 0) {
            merchantIds.add(String.valueOf(merchantId));
        }
        // 多商户通用券
        List<MerchantPageVo> merchantVos = merchantApi.listByIds(merchantIds).unpack();
        if (!CollectionUtils.isEmpty(merchantVos)) {
            activeGoodsUseDetailsVo.setMerchantNames(merchantVos.stream().map(MerchantPageVo::getMerchantShortName).collect(Collectors.toList()));
        }

        return activeGoodsUseDetailsVo;
    }

    @Override
    public Page<AdminActivePageVo> pageAdminActive(AdminActivePageDto adminActivePageDto) {
        if (ActiveTabEnum.NORMAL.name().equals(adminActivePageDto.getTab())) {
            // 普通活动：1，2，4
            List<Integer> activeTypes = Arrays.asList(
                    ActiveTypeEnum.GROUP.getValue(), ActiveTypeEnum.ENROLL.getValue(), ActiveTypeEnum.GROUP_ENROLL.getValue());
            adminActivePageDto.setActiveTypes(activeTypes);
            adminActivePageDto.setActiveType(null); // 避免前端多传一个类型，导致查询冲突
        } else if (ActiveTabEnum.EXTERNAL.name().equals(adminActivePageDto.getTab())) {
            adminActivePageDto.setActiveType(ActiveTypeEnum.EXTERNAL.getValue());
        } else if (ActiveTabEnum.GROUP_BUY.name().equals(adminActivePageDto.getTab())) {
            adminActivePageDto.setActiveType(null);
        }

        adminActivePageDto.setNowTime(LocalDateUtil.toLocalDateTimeToString(LocalDateTime.now(), Constant.YYYY_MM_DD_HH_MM_SS));
        PageHelper.startPage(adminActivePageDto.getPageNum(), adminActivePageDto.getPageSize());
        List<AdminActivePageVo> adminActivePageVos = baseMapper.listAdminActiveByDto(adminActivePageDto);
        if (!CollectionUtils.isEmpty(adminActivePageVos)) {
            List<Long> activeIds = adminActivePageVos.stream().map(AdminActivePageVo::getId).collect(Collectors.toList());
            List<Long> businessIds = adminActivePageVos.stream().map(AdminActivePageVo::getBusinessId).collect(Collectors.toList());

            // 查询商家数据
            Map<Long, BusinessVo> businessVoMap = new HashMap<>();
            List<BusinessVo> businessVos = businessApi.listByIds(businessIds).unpack();
            if (!CollectionUtils.isEmpty(businessVos)) {
                businessVoMap = businessVos.stream().collect(Collectors.toMap(BusinessVo::getId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询活动商品列表
            Map<Long, List<ActiveGoodsSonDto>> adminActiveGoodsSonMap = new HashMap<>();
            List<ActiveGoodsSonDto> adminActiveGoodsSons = activeGoodsMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(adminActiveGoodsSons)) {
                adminActiveGoodsSonMap = adminActiveGoodsSons.stream().collect(Collectors.groupingBy(ActiveGoodsSonDto::getActiveId));
            }

            // 查询阶梯价格列表
            Map<Long, List<ActiveStepPriceSonDto>> activeStepPriceSonDtoMap = new HashMap<>();
            List<ActiveStepPriceSonDto> activeStepPriceSonDtos = activeStepPriceMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeStepPriceSonDtos)) {
                activeStepPriceSonDtoMap = activeStepPriceSonDtos.stream().collect(Collectors.groupingBy(ActiveStepPriceSonDto::getActiveId));
            }

            // 查询已报名人数
            Map<Long, List<OrderItemVo>> tbActiveEnrollOrderItemMap = new HashMap<>();
            List<OrderItemVo> tbActiveEnrollOrderItems = orderItemApi.listByActiveIds(activeIds).unpack();
            if (!CollectionUtils.isEmpty(tbActiveEnrollOrderItems)) {
                tbActiveEnrollOrderItemMap = tbActiveEnrollOrderItems.stream().collect(Collectors.groupingBy(OrderItemVo::getActiveId));
            }

            for (AdminActivePageVo adminActivePageVo : adminActivePageVos) {
                Integer activeType = adminActivePageVo.getActiveType();

                // 处理商家名称
                BusinessVo businessVo = businessVoMap.get(adminActivePageVo.getBusinessId());
                if (businessVo != null) {
                    adminActivePageVo.setBusinessName(businessVo.getBusinessName());
                    adminActivePageVo.setBusinessShortName(businessVo.getBusinessShortName());
                }

                // 根据活动时间处理已发布的活动状态
                Integer activeState = adminActivePageVo.getActiveState();
                if (!ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)) {
                    LocalDateTime startTime = adminActivePageVo.getStartTime();
                    LocalDateTime endTime = adminActivePageVo.getEndTime();
                    LocalDateTime now = LocalDateTime.now();
                    if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
                        activeState = ActiveStateEnum.IN_PROGRESS.getValue();
                    } else if (endTime.compareTo(now) <= 0) {
                        activeState = ActiveStateEnum.ENDED.getValue();
                    } else if (startTime.compareTo(now) > 0) {
                        activeState = ActiveStateEnum.NO_START.getValue();
                    }
                }
                adminActivePageVo.setActiveState(activeState);

                Boolean isPft = false;
                // 如果是团购活动
                if (ActiveTypeEnum.GROUP.getValue().equals(activeType)) {
                    // 计算商品总价
                    BigDecimal totalPrice = BigDecimal.ZERO;
                    List<ActiveGoodsSonDto> adminActiveGoodsSonDtos = adminActiveGoodsSonMap.get(adminActivePageVo.getId());
                    if (!CollectionUtils.isEmpty(adminActiveGoodsSonDtos)) {
                        for (ActiveGoodsSonDto adminActiveGoodsSonDto : adminActiveGoodsSonDtos) {
                            BigDecimal goodsPrice = adminActiveGoodsSonDto.getGoodsPrice();
                            totalPrice = totalPrice.add(goodsPrice);
                            if (VerifyTypeEnum.TYF.getValue().equals(adminActiveGoodsSonDto.getVerifyType())) {
                                isPft = true;
                            }
                        }
                    }

                    adminActivePageVo.setTotalPrice(totalPrice);
                }

                // 如果是报名活动
                if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
                    // 获取报名人数
                    List<OrderItemVo> tbActiveEnrollOrderItemList = tbActiveEnrollOrderItemMap.get(adminActivePageVo.getId());
                    adminActivePageVo.setEnrolledNum(CollectionUtils.isEmpty(tbActiveEnrollOrderItemList) ? 0 : tbActiveEnrollOrderItemList.size());

                    // 获取阶梯价格
                    List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceSonDtoMap.get(adminActivePageVo.getId());
                    if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
                        adminActivePageVo.setActiveStepPrices(activeStepPriceSonDtoList);

                        // 将阶梯价格的最高价设置为活动价格显示
//                        adminActivePageVo.setActivePrice(getMaxStepPrice(activeStepPriceSonDtoList));
                    }
                    if (VerifyTypeEnum.TYF.getValue().equals(adminActivePageVo.getVerifyType())) {
                        isPft = true;
                    }
                }
                adminActivePageVo.setIsPft(isPft);
            }
        }

        // 拼团信息
        processAdminGroupBuyActives(adminActivePageVos);

        PageInfo<AdminActivePageVo> pageInfo = new PageInfo<>(adminActivePageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    // 处理后台拼团活动信息
    private void processAdminGroupBuyActives(List<AdminActivePageVo> adminActivePageList) {
        if (CollectionUtils.isEmpty(adminActivePageList)) {
            return;
        }
        List<Long> activeIds = adminActivePageList.stream().map(AdminActivePageVo::getId).collect(Collectors.toList());
        List<TbActiveGroupBuyPo> tbActiveGroupBuyPos = activeGroupBuyService.listByActiveIds(activeIds);
        Map<Long, TbActiveGroupBuyPo> activeIdToGroupBuyMap = tbActiveGroupBuyPos.stream()
                .collect(Collectors.toMap(TbActiveGroupBuyPo::getActiveId, Function.identity()));

        // 拼团价格、成团人数
        for (AdminActivePageVo adminActivePageVo : adminActivePageList) {
            TbActiveGroupBuyPo tbActiveGroupBuyPo = activeIdToGroupBuyMap.get(adminActivePageVo.getId());
            if (tbActiveGroupBuyPo != null) {
                adminActivePageVo.setActivePrice(tbActiveGroupBuyPo.getGroupBuyPrice());
                adminActivePageVo.setGroupNum(tbActiveGroupBuyPo.getGroupNum());
            }
        }
        // 开团数、成团数
        List<GroupBuyOrderNumStatVo> groupBuyOrderNumStatVos = orderApi.statisticsGroupOrderNumByActiveIds(activeIds).unpack();
        if (!CollectionUtils.isEmpty(groupBuyOrderNumStatVos)) {
            Map<Long, GroupBuyOrderNumStatVo> activeIdToOrderNumMap = groupBuyOrderNumStatVos.stream()
                    .collect(Collectors.toMap(GroupBuyOrderNumStatVo::getActiveId, Function.identity()));
            for (AdminActivePageVo adminActivePageVo : adminActivePageList) {
                GroupBuyOrderNumStatVo groupBuyOrderNumStatVo = activeIdToOrderNumMap.get(adminActivePageVo.getId());
                if (groupBuyOrderNumStatVo != null) {
                    adminActivePageVo.setGroupOrderNum(groupBuyOrderNumStatVo.getGroupOrderNum());
                    adminActivePageVo.setSuccessfulGroupOrderNum(groupBuyOrderNumStatVo.getSuccessfulGroupOrderNum());
                }
            }
        }

    }

    @Override
    public AdminActivePageVo adminDetails(Long id) {
        TbActivePo tbActivePo = baseMapper.selectById(id);
        if (tbActivePo == null || tbActivePo.getDelState() != 0) {
            Throw.isBusinessException("未找到活动数据");
        }
        AdminActivePageVo adminActivePageVo = new AdminActivePageVo();
        BeanUtils.copyProperties(tbActivePo, adminActivePageVo);

        adminActivePageVo.setLabels(activeLabelService.getActiveLabels(id));

        // 根据活动时间处理已发布的活动状态
        Integer activeState = adminActivePageVo.getActiveState();
        if (!ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)) {
            LocalDateTime startTime = adminActivePageVo.getStartTime();
            LocalDateTime endTime = adminActivePageVo.getEndTime();
            LocalDateTime now = LocalDateTime.now();
            if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
                activeState = ActiveStateEnum.IN_PROGRESS.getValue();
            } else if (endTime.compareTo(now) <= 0) {
                activeState = ActiveStateEnum.ENDED.getValue();
            } else if (startTime.compareTo(now) > 0) {
                activeState = ActiveStateEnum.NO_START.getValue();
            }
        }
        adminActivePageVo.setActiveState(activeState);

        // 查询商家数据
        List<BusinessVo> businessVos = businessApi.listByIds(Collections.singletonList(tbActivePo.getBusinessId())).unpack();
        if (!CollectionUtils.isEmpty(businessVos)) {
            adminActivePageVo.setBusinessName(businessVos.get(0).getBusinessName());
            adminActivePageVo.setBusinessShortName(businessVos.get(0).getBusinessShortName());
        }

        Integer activeType = tbActivePo.getActiveType();
        if (ActiveTypeEnum.EXTERNAL.getValue().equals(activeType)) {
            return adminActivePageVo;
        }

        Boolean isPft = false;
        if (ActiveTypeEnum.GROUP.getValue().equals(activeType)) {
            setAdminGroupGoodsInfo(id, tbActivePo, adminActivePageVo);
        } else if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
            setAdminEnrollInfo(id, tbActivePo, adminActivePageVo);
        } else if (ActiveTypeEnum.GROUP_ENROLL.getValue().equals(activeType)) {
            setAdminGroupGoodsInfo(id, tbActivePo, adminActivePageVo);
            setAdminEnrollInfo(id, tbActivePo, adminActivePageVo);
        }

        if (VerifyTypeEnum.TYF.getValue().equals(adminActivePageVo.getVerifyType())) {
            adminActivePageVo.setIsPft(true);
        } else {
            adminActivePageVo.setIsPft(false);
        }

        // 新人首单红包
        List<ActiveRedPacketSonDto> activeRedPackets = activeRedPacketMapper.listByActiveIds(Collections.singletonList(id));
        if (!CollectionUtils.isEmpty(activeRedPackets)) {
            ActiveRedPacketSonDto activeRedPacketSonDto = activeRedPackets.get(0);
            AdminActiveRedPacketSonDto adminActiveRedPacketSonDto = new AdminActiveRedPacketSonDto();
            BeanUtils.copyProperties(activeRedPacketSonDto, adminActiveRedPacketSonDto);

            int useNum = 0;
            int receiveNum = 0;
            List<TbActiveRedPacketBillPo> tbActiveRedPacketBillPos = activeRedPacketBillMapper.selectList(new QueryWrapper<TbActiveRedPacketBillPo>()
                    .eq("del_state", 0).eq("active_id", id));
            if (!CollectionUtils.isEmpty(tbActiveRedPacketBillPos)) {
                receiveNum = tbActiveRedPacketBillPos.size();
                for (TbActiveRedPacketBillPo tbActiveRedPacketBillPo : tbActiveRedPacketBillPos) {
                    if (ActiveRedPacketStateEnum.YES_UES.getValue().equals(tbActiveRedPacketBillPo.getState())
                            || ActiveRedPacketStateEnum.YES_VERIFY.getValue().equals(tbActiveRedPacketBillPo.getState())) {
                        useNum += 1;
                    }
                }
            }

            adminActiveRedPacketSonDto.setReceiveNum(receiveNum);
            adminActiveRedPacketSonDto.setUseNum(useNum);
            adminActivePageVo.setActiveRedPacket(adminActiveRedPacketSonDto);
        }

        if (PromotionTypeEnum.GROUP_BUY.name().equals(adminActivePageVo.getPromotionType())) {
            TbActiveGroupBuyPo activeGroupBuy = activeGroupBuyService.getByActiveId(adminActivePageVo.getId());
            adminActivePageVo.setActiveGroupBuyVo(BeanUtil.copyProperties(activeGroupBuy, ActiveGroupBuyVo.class));
        }

        return adminActivePageVo;
    }

    private void setAdminGroupGoodsInfo(Long id, TbActivePo tbActivePo, AdminActivePageVo adminActivePageVo) {
        Integer subsidyState = tbActivePo.getSubsidyState();
        BigDecimal activePrice = tbActivePo.getActivePrice();

        // 查询活动商品列表
        List<ActiveGoodsSonDto> adminActiveGoodsSons = activeGoodsMapper.listByActiveIds(Collections.singletonList(id));
        Map<String, ActiveGoodsSonDto> activeGoodsSonDtoMap = new HashMap<>();

        List<String> merchantIds = new ArrayList<>();
        // 计算商品总价
        BigDecimal totalPrice = BigDecimal.ZERO;
        if (!CollectionUtils.isEmpty(adminActiveGoodsSons)) {
            activeGoodsSonDtoMap = adminActiveGoodsSons.stream()
                    .collect(Collectors.toMap(ActiveGoodsSonDto::getGoodsId, Function.identity(), (k1, k2) -> k2));
            for (ActiveGoodsSonDto adminActiveGoodsSon : adminActiveGoodsSons) {
                Integer goodsNum = adminActiveGoodsSon.getGoodsNum();
                BigDecimal goodsPrice = adminActiveGoodsSon.getGoodsPrice();
                totalPrice = totalPrice.add(goodsPrice.multiply(new BigDecimal(goodsNum)));

                if (MulStateEnum.NO.getValue().equals(adminActiveGoodsSon.getMulState())) {
                    merchantIds.add(String.valueOf(adminActiveGoodsSon.getMerchantId()));
                }
//                if (VerifyTypeEnum.TYF.getValue().equals(adminActiveGoodsSon.getVerifyType())) {
//                    adminActivePageVo.setIsPft(true);
//                }
            }
        }
        adminActivePageVo.setTotalPrice(totalPrice);

        Map<Long, MerchantPageVo> merchantMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(merchantIds)) {
            List<MerchantPageVo> merchants = merchantApi.listByIds(merchantIds).unpack();
            if (!CollectionUtils.isEmpty(merchants)) {
                merchantMap = merchants.stream().collect(Collectors.toMap(MerchantPageVo::getId, Function.identity(), (k1, k2) -> k2));
            }
        }

        // 计算补贴金额
        if (SubsidyStateEnum.AUTO.getValue().equals(subsidyState)) {
            // 自动按比例计算补贴金额

            // 总的补贴金额=商品总价-活动价格
            BigDecimal totalSubsidyAmt = totalPrice.subtract(activePrice);
            if (totalSubsidyAmt.compareTo(BigDecimal.ZERO) > 0) {
                for (ActiveGoodsSonDto adminActiveGoodsSon : adminActiveGoodsSons) {
                    Integer goodsNum = adminActiveGoodsSon.getGoodsNum();
                    BigDecimal goodsPrice = adminActiveGoodsSon.getGoodsPrice();
                    // 商家单价/活动价格*总补贴金额
                    BigDecimal singGoodsSubsidyAmt = goodsPrice.divide(totalPrice, 2, BigDecimal.ROUND_HALF_UP).multiply(totalSubsidyAmt);

                    // 多件相同的商品的补贴价格
                    adminActiveGoodsSon.setSubsidyAmt(singGoodsSubsidyAmt.multiply(new BigDecimal(goodsNum)));
                }
            }

        } else if (SubsidyStateEnum.MANUAL.getValue().equals(subsidyState)) {
            // 手动设置补贴金额
            List<ActiveGoodsSubsidySonDto> activeGoodsSubsidySonDtos = activeGoodsSubsidyMapper.listByActiveId(id);
            if (!CollectionUtils.isEmpty(activeGoodsSubsidySonDtos)) {
                for (ActiveGoodsSubsidySonDto activeGoodsSubsidySonDto : activeGoodsSubsidySonDtos) {
                    String goodsId = activeGoodsSubsidySonDto.getGoodsId();
                    BigDecimal subsidyAmt = activeGoodsSubsidySonDto.getSubsidyAmt();

                    if (activeGoodsSonDtoMap.containsKey(goodsId)) {
                        ActiveGoodsSonDto activeGoodsSonDto = activeGoodsSonDtoMap.get(goodsId);
                        BigDecimal getSubsidyAmt = activeGoodsSonDto.getSubsidyAmt();
                        if (getSubsidyAmt == null) {
                            getSubsidyAmt = BigDecimal.ZERO;
                        }
                        activeGoodsSonDto.setSubsidyAmt(getSubsidyAmt.add(subsidyAmt));
                        activeGoodsSonDtoMap.put(goodsId, activeGoodsSonDto);
                    }
                }
            }
        }

        // 设置所属商户名称
        for (ActiveGoodsSonDto adminActiveGoodsSon : adminActiveGoodsSons) {
            Integer mulState = adminActiveGoodsSon.getMulState();
            if (MulStateEnum.YES.getValue().equals(mulState)) {
                // 如果是多商户通用券，则所属商户显示适用x家
                adminActiveGoodsSon.setMerchantName(String.format("适用%s家", adminActiveGoodsSon.getGoodsId().split(",").length));
            } else {
                MerchantPageVo merchantPageVo = merchantMap.get(adminActiveGoodsSon.getMerchantId());
                if (merchantPageVo != null) {
                    adminActiveGoodsSon.setMerchantName(merchantPageVo.getMerchantShortName());
                }
            }
        }

        adminActivePageVo.setActiveGoods(adminActiveGoodsSons);
    }

    private void setAdminEnrollInfo(Long id, TbActivePo tbActivePo, AdminActivePageVo adminActivePageVo) {
        Integer stepPriceState = tbActivePo.getStepPriceState();
        if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
            // 查询阶梯价格列表
            List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceMapper.listByActiveIds(Collections.singletonList(id));
            adminActivePageVo.setActiveStepPrices(activeStepPriceSonDtoList);

            // 将阶梯价格的最高价设置为活动价格显示
            BigDecimal maxStepPrice = getMaxStepPrice(activeStepPriceSonDtoList);
            if (adminActivePageVo.getActivePrice().compareTo(BigDecimal.ZERO) == 0
                    && maxStepPrice.compareTo(BigDecimal.ZERO) > 0) {
                adminActivePageVo.setActivePrice(maxStepPrice);
            }
        }

        // 报名信息列表
        List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeEnrollInfoMapper.listByActiveId(id);
        if (!CollectionUtils.isEmpty(activeEnrollInfos)) {
            for (ActiveEnrollInfoSonDto activeEnrollInfo : activeEnrollInfos) {
                if (ActiveEnrollInfoTypeEnum.WRITE.getValue().equals(activeEnrollInfo.getType())) {
                    continue;
                }

                String content = activeEnrollInfo.getContent();
                if (StringUtils.isEmpty(content)) {
                    continue;
                }

                activeEnrollInfo.setActiveEnrollInfoOptions(JSON.parseArray(content, ActiveEnrollInfoOptionDto.class));
                activeEnrollInfo.setContent("");
            }
        }
        adminActivePageVo.setActiveEnrollInfos(activeEnrollInfos);

        // 查询已报名人数
        List<OrderItemVo> tbActiveEnrollOrderItemList = orderItemApi.listByActiveIds(Collections.singletonList(id)).unpack();
        long count = tbActiveEnrollOrderItemList.stream().filter(e -> (e.getEnrollInfo() != null || OrderItemTypeEnum.SIGN_IN.getValue().equals(e.getItemType())))
                .count();
        adminActivePageVo.setEnrolledNum((int) count);

//        if (VerifyTypeEnum.TYF.getValue().equals(adminActivePageVo.getVerifyType())) {
//            adminActivePageVo.setIsPft(true);
//        }

    }

    @Override
    public List<SearchBusinessActiveVo> listSearchBusinessActive(List<Long> businessIds) {
        List<Integer> activeStates = Arrays.asList(ActiveStateEnum.NO_START.getValue(), ActiveStateEnum.IN_PROGRESS.getValue());
        String nowTime = LocalDateUtil.toLocalDateTimeToString(LocalDateTime.now(), Constant.YYYY_MM_DD_HH_MM_SS);
        return baseMapper.listSearchBusinessActive(businessIds, activeStates, nowTime);
    }

    @Override
    public Integer countByBusinessId(Long businessId) {
        return baseMapper.selectCount(new QueryWrapper<TbActivePo>().eq("del_state", 0).eq("business_id", businessId));
    }

    @Override
    public Page<BusinessHomeActivePageVo> pageHomeActive(BusinessHomeActivePageDto businessHomeActivePageDto) {
        // 类型：1-全部活动，2-可推广的活动
        Integer type = businessHomeActivePageDto.getType();
        // 当前访问的商家id
        Long ownBusinessId = businessHomeActivePageDto.getOwnBusinessId();
        // 查看的商家id
        Long businessId = businessHomeActivePageDto.getBusinessId();
        Long userId = businessHomeActivePageDto.getUserId();

        LocalDateTime now = LocalDateTime.now();

        // 判断是否是商家访问，如果是商家访问，返回所有的活动数据，否则，返回进行中的活动
        if (ownBusinessId == null || !ownBusinessId.equals(businessId)) {
            // 不是商家访问自己的商家主页，返回进行中的活动
            List<Integer> activeStates = Arrays.asList(ActiveStateEnum.NO_START.getValue(),
                    ActiveStateEnum.IN_PROGRESS.getValue());

            if (type == null || type == 1) {
                // 如果选择的是全部活动，则返回进行中和已结束的的活动
                activeStates = Arrays.asList(ActiveStateEnum.NO_START.getValue(),
                        ActiveStateEnum.IN_PROGRESS.getValue(),
                        ActiveStateEnum.ENDED.getValue());
            } else {
                // 如果是可推广的活动，只返回进行中的活动
                // 如果是可推广的活动，查询需要满足下面条件
                //  1、活动分销开启状态=开启
                //  2、如果是所有经纪人都可推广，需要查询商家经纪人关联表，判断当前登录用户是否是该活动商家的经纪人，如果是则返回
                //  3、如果不是所有经纪人都可推广，需要查询活动经纪人关联表，判断当前登录用户是否是该活动的分佣经纪人，如果是则返回
                businessHomeActivePageDto.setNowTime(now);
            }

            businessHomeActivePageDto.setActiveStates(activeStates);
        }

        if (userId == null || userId <= 0) {
            // 未登录的用户查看商家主页（与用户点击商家分享主页链接相同），显示进行中和已结束的活动列表，分享，除了查看活动详情外的操作，都需要登录
            businessHomeActivePageDto.setActiveStates(Arrays.asList(ActiveStateEnum.NO_START.getValue(),
                    ActiveStateEnum.IN_PROGRESS.getValue(),
                    ActiveStateEnum.ENDED.getValue()));
        }

        // 分页条件查询活动数据
        PageHelper.startPage(businessHomeActivePageDto.getPageNum(), businessHomeActivePageDto.getPageSize());
        List<BusinessHomeActivePageVo> activePageVos = baseMapper.listHomeActiveByDto(businessHomeActivePageDto);
        if (!CollectionUtils.isEmpty(activePageVos)) {
            List<Long> activeIds = activePageVos.stream().map(BusinessHomeActivePageVo::getId).collect(Collectors.toList());
            List<Long> businessIds = activePageVos.stream().map(BusinessHomeActivePageVo::getBusinessId).collect(Collectors.toList());

            // 查询多件多折列表
            Map<Long, List<ActiveDiscountSonDto>> tbActiveDiscountPoMap = new HashMap<>();
            List<ActiveDiscountSonDto> tbActiveDiscountPos = activeDiscountMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(tbActiveDiscountPos)) {
                tbActiveDiscountPoMap = tbActiveDiscountPos.stream().collect(Collectors.groupingBy(ActiveDiscountSonDto::getActiveId));
            }

            // 查询新人首单红包数据
            Map<Long, ActiveRedPacketSonDto> activeRedPacketSonDtoMap = new HashMap<>();
            List<ActiveRedPacketSonDto> activeRedPacketSonDtoList = activeRedPacketMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeRedPacketSonDtoList)) {
                activeRedPacketSonDtoMap = activeRedPacketSonDtoList.stream().collect(Collectors.toMap(ActiveRedPacketSonDto::getActiveId, Function.identity(), (k1, k2) -> k2));
            }

            // 查询阶梯价格列表
            Map<Long, List<ActiveStepPriceSonDto>> activeStepPriceSonDtoMap = new HashMap<>();
            List<ActiveStepPriceSonDto> activeStepPriceSonDtos = activeStepPriceMapper.listByActiveIds(activeIds);
            if (!CollectionUtils.isEmpty(activeStepPriceSonDtos)) {
                activeStepPriceSonDtoMap = activeStepPriceSonDtos.stream().collect(Collectors.groupingBy(ActiveStepPriceSonDto::getActiveId));
            }

            Map<Long, List<TbActiveBrowseStatisticsPo>> tbActiveBrowseStatisticsPoMap = new HashMap<>();
            Map<Long, List<OrderVo>> orderMap = new HashMap<>();
            Map<Long, List<OrderItemVo>> orderItemMap = new HashMap<>();

//            if (ownBusinessId != null && ownBusinessId.equals(businessId)) {
            // 如果是商家自己访问商家主页，则要返回统计数据

            // 根据活动id查询订单数据
            OrderDto orderDto = new OrderDto();
            orderDto.setActiveIds(activeIds);
            orderDto.setOrderStates(Arrays.asList(OrderStateEnum.WAIT_VERIFY.getValue(),
                    OrderStateEnum.VERIFYING.getValue(),
                    OrderStateEnum.FINISH.getValue(),
                    OrderStateEnum.VERIFIED.getValue()));
            List<OrderVo> orderVos = orderApi.listByDto(orderDto).unpack();
            if (!CollectionUtils.isEmpty(orderVos)) {
                orderMap = orderVos.stream().collect(Collectors.groupingBy(OrderVo::getActiveId));
            }

            OrderItemDto orderItemDto = new OrderItemDto();
            orderItemDto.setActiveIds(activeIds);
            orderItemDto.setSubOrderStates(Arrays.asList(SubOrderStateEnum.WAIT_VERIFY.getValue(),
                    SubOrderStateEnum.VERIFIED.getValue()));
            List<OrderItemVo> orderItemVos = orderItemApi.listByDto(orderItemDto).unpack();
            if (!CollectionUtils.isEmpty(orderItemVos)) {
                orderItemMap = orderItemVos.stream().collect(Collectors.groupingBy(OrderItemVo::getActiveId));
            }
//            }

            // 根据活动id查询活动浏览数
            List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPos = activeBrowseStatisticsMapper.selectList(new QueryWrapper<TbActiveBrowseStatisticsPo>()
                    .eq("del_state", 0)
                    .in("active_id", activeIds));
            if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPos)) {
                tbActiveBrowseStatisticsPoMap = tbActiveBrowseStatisticsPos.stream().collect(Collectors.groupingBy(TbActiveBrowseStatisticsPo::getActiveId));
            }

            Map<Long, List<BusinessAgentVo>> businessAgentMap = new HashMap<>();
            Map<Long, List<TbActiveAgentPo>> activeAgentMap = new HashMap<>();
            if (userId != null && userId > 0) {
                List<BusinessAgentVo> businessAgentVoList = businessAgentApi.listByBusinessIds(businessIds).unpack();
                if (!CollectionUtils.isEmpty(businessAgentVoList)) {
                    businessAgentMap = businessAgentVoList.stream().collect(Collectors.groupingBy(BusinessAgentVo::getBusinessId));
                }

                List<TbActiveAgentPo> activeAgentPos = activeAgentMapper.listByActiveIds(activeIds);
                if (!CollectionUtils.isEmpty(activeAgentPos)) {
                    activeAgentMap = activeAgentPos.stream().collect(Collectors.groupingBy(TbActiveAgentPo::getActiveId));
                }
            }

            for (BusinessHomeActivePageVo activePageVo : activePageVos) {
                Long id = activePageVo.getId();
                List<ActiveDiscountSonDto> activeDiscountSonDtoList = tbActiveDiscountPoMap.get(id);
                if (!CollectionUtils.isEmpty(activeDiscountSonDtoList)) {
                    activePageVo.setActiveDiscount(activeDiscountSonDtoList);
                }

                ActiveRedPacketSonDto activeRedPacketSonDto = activeRedPacketSonDtoMap.get(id);
                if (activeRedPacketSonDto != null) {
                    activePageVo.setActiveRedPacket(activeRedPacketSonDto);
                }

                List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceSonDtoMap.get(id);
                if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
                    activePageVo.setActiveStepPrices(activeStepPriceSonDtoList);

                    // 将阶梯价格的最高价设置为活动价格显示
//                    activePageVo.setActivePrice(getMaxStepPrice(activeStepPriceSonDtoList));
                }

                // 对未开始和进行中的活动状态处理
                Integer activeState = activePageVo.getActiveState();
                if (ActiveStateEnum.NO_START.getValue().equals(activeState) || ActiveStateEnum.IN_PROGRESS.getValue().equals(activeState)) {
                    LocalDateTime startTime = activePageVo.getStartTime();
                    LocalDateTime endTime = activePageVo.getEndTime();

                    if (startTime.compareTo(now) > 0) {
                        activePageVo.setActiveState(ActiveStateEnum.NO_START.getValue());
                    } else if (endTime.compareTo(now) <= 0) {
                        activePageVo.setActiveState(ActiveStateEnum.ENDED.getValue());
                    } else if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
                        activePageVo.setActiveState(ActiveStateEnum.IN_PROGRESS.getValue());
                    }
                }

                List<TbActiveBrowseStatisticsPo> tbActiveBrowseStatisticsPoList = tbActiveBrowseStatisticsPoMap.get(id);
                if (!CollectionUtils.isEmpty(tbActiveBrowseStatisticsPoList)) {
                    activePageVo.setBrowseNum(tbActiveBrowseStatisticsPoList.stream().mapToLong(TbActiveBrowseStatisticsPo::getBrowseNum).sum());
                }

                BigDecimal commissionAmt = activePageVo.getCommissionAmt();
                BigDecimal commissionRate = activePageVo.getCommissionRate();
                String otherEquity = activePageVo.getOtherEquity();
                // 对显示可得佣金处理（只有当前用户是该商家的经纪人，且有该活动分销权限时，显示权益）
                if (userId != null && userId > 0) {
                    // 是否是所有经纪人可推广：1-是，2-否
                    Integer agentNumState = activePageVo.getAgentNumState();
                    List<Long> agentIds = new ArrayList<>();
                    if (AgentNumStateEnum.YES.getValue().equals(agentNumState)) {
                        // 查询商家经纪人关联数据
                        List<BusinessAgentVo> businessAgentVos = businessAgentMap.get(activePageVo.getBusinessId());
                        if (!CollectionUtils.isEmpty(businessAgentVos)) {
                            agentIds = businessAgentVos.stream().map(BusinessAgentVo::getUserId).collect(Collectors.toList());
                        }
                    } else {
                        // 查询活动分销经纪人列表
                        List<TbActiveAgentPo> activeAgentPoList = activeAgentMap.get(id);
                        if (!CollectionUtils.isEmpty(activeAgentPoList)) {
                            agentIds = activeAgentPoList.stream().map(TbActiveAgentPo::getAgentId).collect(Collectors.toList());
                        }
                    }

                    if (!CollectionUtils.isEmpty(agentIds) && agentIds.contains(userId)) {
                        BigDecimal activePrice = activePageVo.getActivePrice();
                        // 默认佣金类型：0-无，1-佣金，2-佣金比例
                        Integer defaultCommissionType = activePageVo.getDefaultCommissionType();
                        if (defaultCommissionType != null) {
                            if (DefaultCommissionTypeEnum.NULL.getValue().equals(defaultCommissionType)) {
                                commissionAmt = BigDecimal.ZERO;
                            } else if (DefaultCommissionTypeEnum.COMMISSION.getValue().equals(defaultCommissionType)) {
                                otherEquity = "";
                            } else if (DefaultCommissionTypeEnum.COMMISSION_RATE.getValue().equals(defaultCommissionType)) {
                                commissionAmt = activePrice.multiply(commissionRate).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
                                otherEquity = "";
                            }
                        }
                    } else {
                        commissionAmt = BigDecimal.ZERO;
                        commissionRate = BigDecimal.ZERO;
                        otherEquity = "";
                    }
                } else {
                    commissionAmt = BigDecimal.ZERO;
                    commissionRate = BigDecimal.ZERO;
                    otherEquity = "";
                }

                activePageVo.setCommissionAmt(commissionAmt);
                activePageVo.setCommissionRate(commissionRate);
                activePageVo.setOtherEquity(otherEquity);

                // 购买人数
                int buyNum = 0;
                List<OrderVo> orderVoList = orderMap.get(id);
                if (!CollectionUtils.isEmpty(orderVoList)) {
                    // 购买人数
                    buyNum = orderVoList.stream().mapToInt(OrderVo::getOrderNum).sum();
                }
                activePageVo.setBuyNum(buyNum + activePageVo.getSaleNum());

                if (ownBusinessId != null && ownBusinessId.equals(businessId)) {
                    // 如果是商家自己访问商家主页，则要返回统计数据

                    // 成交数
                    int tradeNum = 0;
                    // 成交金额
                    BigDecimal tradeAmt = BigDecimal.ZERO;
                    // 分销订单数
                    int distributeOrderNum = 0;
                    // 分销佣金
                    BigDecimal distributeOrderAmt = BigDecimal.ZERO;

                    orderVos = orderMap.get(id);
                    if (!CollectionUtils.isEmpty(orderVos)) {
                        for (OrderVo orderVo : orderVos) {
                            Long agentId = orderVo.getAgentId();
                            if (agentId != null && agentId > 0) {
                                // 分销订单数
                                distributeOrderNum += 1;
                            }

                            // 成交数
                            tradeNum += 1;
                            // 成交金额 = 实付金额
                            tradeAmt = tradeAmt.add(orderVo.getActivePrice());
                        }
                    }

                    List<OrderItemVo> orderItemVoList = orderItemMap.get(id);
                    if (!CollectionUtils.isEmpty(orderItemVoList)) {
                        for (OrderItemVo orderItemVo : orderItemVoList) {
                            // 分销佣金
                            distributeOrderAmt = distributeOrderAmt.add(orderItemVo.getCommissionAmt());
                        }
                    }

                    activePageVo.setTradeNum(tradeNum);
                    activePageVo.setTradeAmt(tradeAmt);
                    activePageVo.setDistributeOrderNum(distributeOrderNum);
                    activePageVo.setDistributeOrderAmt(distributeOrderAmt);
                }
            }
        }

        // 拼团标识
        processBusinessHomeActivesGroupBuyTag(activePageVos);

        PageInfo<BusinessHomeActivePageVo> pageInfo = new PageInfo<>(activePageVos);
        return Page.newPageWithAllFields(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getPages());
    }

    private void processBusinessHomeActivesGroupBuyTag(List<BusinessHomeActivePageVo> dataList) {
        if (CollectionUtils.isEmpty(dataList)) {
            return;
        }
        List<Long> activeIds = dataList.stream()
                .filter(e -> PromotionTypeEnum.GROUP_BUY.name().equals(e.getPromotionType()))
                .map(BusinessHomeActivePageVo::getId)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activeIds)) {
            return;
        }
        Map<Long, TbActiveGroupBuyPo> activeIdToGroupBuyInfo = activeGroupBuyService.listByActiveIds(activeIds)
                .stream()
                .collect(Collectors.toMap(TbActiveGroupBuyPo::getActiveId, Function.identity()));
        for (BusinessHomeActivePageVo pageVo : dataList) {
            TbActiveGroupBuyPo groupBuyInfo = activeIdToGroupBuyInfo.get(pageVo.getId());
            if (groupBuyInfo != null) {
                pageVo.setPromotionLabel(groupBuyInfo.getGroupNum() + "人团");
            }
        }
    }

    @Override
    public ActivePreShareVo preShareActive(ActivePreShareDto activePreShareDto) {
        ActivePreShareVo activePreShareVo = new ActivePreShareVo();
        Long id = activePreShareDto.getId();
        Long agent1Id = activePreShareDto.getAgent1Id();
        Long agent2Id = activePreShareDto.getAgent2Id();
        if (id == null || id <= 0) {
            Throw.isBusinessException("请选择活动");
        }

        // 需要对活动id加锁
        String lockKey = MessageFormat.format(Constant.LOCK_FORMAT, "preShareActive:" + id);
        try {
            LockUtils.blockLock(lockKey, Constant.AUTO_UNLOCK_SECOND);

            // 查询活动是否存在，判断是否有效，是否结束
            TbActivePo tbActivePo = baseMapper.selectById(id);
            if (tbActivePo == null || tbActivePo.getDelState() != 0) {
                Throw.isBusinessException("未找到活动");
            }
            Long businessId = tbActivePo.getBusinessId();

            Integer activeState = tbActivePo.getActiveState();
            if (ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)) {
                Throw.isBusinessException("活动未发布");
            }

//            if (ActiveStateEnum.ENDED.getValue().equals(activeState)) {
//                Throw.isBusinessException("活动已结束");
//            }

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime startTime = tbActivePo.getStartTime();
//            LocalDateTime endTime = tbActivePo.getEndTime();

            // 未开始也能分享，注释掉
//            if (startTime.compareTo(now) >= 0) {
//                Throw.isBusinessException("活动未开始");
//            }

//            if (endTime.compareTo(now) <= 0) {
//                Throw.isBusinessException("活动已结束");
//            }

//            Integer remainStock = tbActivePo.getRemainStock();
//            if (remainStock <= 0) {
//                Throw.isBusinessException("参团人数已满");
//            }

            // 分销开启状态(1-关闭，2-开启)
            Integer agentState = tbActivePo.getAgentState();
            if (AgentStateEnum.CLOSE.getValue().equals(agentState)) {
                return activePreShareVo;
            }

            // 一级经纪人跟商家的佣金比例, 小于0表示不能分销
            BigDecimal commissionRate = businessAgentApi.getAgentCommissionRate(agent1Id, businessId).unpack();
            if (commissionRate.compareTo(BigDecimal.ZERO) < 0) {
                return activePreShareVo;
            }

            // 是否是所有经纪人可推广：1-是，2-否
            if (AgentNumStateEnum.NO.getValue().equals(tbActivePo.getAgentNumState())) {
                // 查询活动分销经纪人列表
                List<Long> agentIds = activeAgentMapper.listByActiveId(id);

                // 判断当前分享的用户是否具备分佣权限
                if (CollectionUtils.isEmpty(agentIds) || !agentIds.contains(agent1Id)) {
                    log.error("当前分享活动的用户不具备分佣权限");
                    return activePreShareVo;
                }
            }

            BigDecimal activePrice = tbActivePo.getActivePrice();
//            Integer activeType = tbActivePo.getActiveType();
//            if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
//                Integer stepPriceState = tbActivePo.getStepPriceState();
//                if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
//                    List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceMapper.listByActiveIds(Collections.singletonList(id));
//                    if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
//                        // 将阶梯价格的最高价设置为活动价格显示
//                        activePrice = getMaxStepPrice(activeStepPriceSonDtoList);
//                    }
//                }
//            }

            // 如果是拼团活动，则用拼团价计算佣金
            if (PromotionTypeEnum.GROUP_BUY.name().equals(tbActivePo.getPromotionType())) {
                TbActiveGroupBuyPo activeGroupBuyPo = activeGroupBuyService.getByActiveId(tbActivePo.getId());
                if (activeGroupBuyPo != null) {
                    activePrice = activeGroupBuyPo.getGroupBuyPrice();
                }
            }

            BigDecimal commissionAmt = tbActivePo.getCommissionAmt();
            BigDecimal actualCommissionRate = tbActivePo.getCommissionRate();
            if (commissionRate.compareTo(BigDecimal.ZERO) > 0) {
                actualCommissionRate = commissionRate;
                commissionAmt = activePrice.multiply(actualCommissionRate).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
            }

            if (agent2Id != null && agent2Id > 0) {
                BigDecimal subCommission = businessAgentApi.getSubAgentCommissionRate(agent2Id, agent1Id).unpack();
                if (subCommission.compareTo(BigDecimal.ZERO) < 0) {
                    return activePreShareVo;
                }
                actualCommissionRate = actualCommissionRate.multiply(subCommission).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
                commissionAmt = commissionAmt.multiply(subCommission).divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_DOWN);
            }

            Integer defaultCommissionType = tbActivePo.getDefaultCommissionType();
            String otherEquity = tbActivePo.getOtherEquity();
            if (DefaultCommissionTypeEnum.NULL.getValue().equals(defaultCommissionType)) {
                return activePreShareVo;
            }
            if (DefaultCommissionTypeEnum.COMMISSION.getValue().equals(defaultCommissionType)) {
                if (commissionAmt == null || commissionAmt.compareTo(BigDecimal.ZERO) < 0) {
                    return activePreShareVo;
                }
            } else if (DefaultCommissionTypeEnum.COMMISSION_RATE.getValue().equals(defaultCommissionType)) {
                if (actualCommissionRate == null || actualCommissionRate.compareTo(BigDecimal.ZERO) < 0) {
                    return activePreShareVo;
                }

                commissionAmt = activePrice.multiply(actualCommissionRate).divide(new BigDecimal("100"), 2, BigDecimal.ROUND_DOWN);
            }

            // 每获得1元佣金，可以获得多少积分
            BusinessPageVo businessPageVo = businessApi.getById(tbActivePo.getBusinessId()).unpack();
            if (businessPageVo == null) {
                Throw.isBusinessException("商家不存在");
            }
            BigDecimal pointsAmt = BigDecimal.ZERO;
            if (businessPageVo.getPointsMallState().equals(BusinessPointsMallStateEnum.OPEN.getValue())) {
                BusinessPointsMallSettingsVo settingsVo = businessPointsMallApi.getSettings(businessId).unpack();
                if (settingsVo != null && settingsVo.getDistribution().compareTo(BigDecimal.ZERO) > 0) {
                    pointsAmt = commissionAmt.multiply(settingsVo.getDistribution());
                }
            }

            int popupState = 0;
            if (!StringUtils.isEmpty(otherEquity)) {
                popupState = popupState + 1;
            }
            if (commissionAmt != null && commissionAmt.compareTo(BigDecimal.ZERO) > 0) {
                popupState = popupState + 1;
            }
            if (pointsAmt.compareTo(BigDecimal.ZERO) > 0) {
                popupState = popupState + 1;
            }

            activePreShareVo.setCommissionAmt(commissionAmt);
            activePreShareVo.setPointsAmt(pointsAmt);
            activePreShareVo.setOtherEquity(otherEquity);
            activePreShareVo.setPopupState(popupState > 1);
            return activePreShareVo;
        } finally {
            LockUtils.unlock(lockKey);
        }
    }

    @Override
    public ActiveShareVo shareActive(ActiveShareDto activeShareDto) {
        Long id = activeShareDto.getId();
        Long userId = activeShareDto.getUserId();
        Long agent1Id = activeShareDto.getAgent1Id();
        Long agent2Id = activeShareDto.getAgent2Id();
        // 推广奖励：0-无，1-佣金，2-权益，3-积分
        Integer type = activeShareDto.getType();
        ActiveShareVo activeShareVo = new ActiveShareVo();

        if (id == null || id <= 0) {
            Throw.isBusinessException("请选择活动");
        }

        // 需要对活动id加锁
        String lockKey = MessageFormat.format(Constant.LOCK_FORMAT, "shareActive:" + id);
        try {
            LockUtils.blockLock(lockKey, Constant.AUTO_UNLOCK_SECOND);

            // 查询活动是否存在，判断是否有效，是否结束
            TbActivePo tbActivePo = baseMapper.selectById(id);
            if (tbActivePo == null || tbActivePo.getDelState() != 0) {
                Throw.isBusinessException("未找到活动");
            }

            // 奖励方式改成从活动取，不通过用户选择
            type = tbActivePo.getRewardType();

            Integer activeState = tbActivePo.getActiveState();
            if (ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)) {
                Throw.isBusinessException("活动未发布");
            }

            if (ActiveStateEnum.ENDED.getValue().equals(activeState)) {
                Throw.isBusinessException("活动已结束");
            }

            LocalDateTime now = LocalDateTime.now();
            LocalDateTime endTime = tbActivePo.getEndTime();
            if (endTime.isBefore(now)) {
                Throw.isBusinessException("活动已结束");
            }

            // 如果是报名活动，需要判断是否开启阶梯价格，如果开启，需要将阶梯最低价格赋值给活动价格
//            Integer activeType = tbActivePo.getActiveType();
//            Integer stepPriceState = tbActivePo.getStepPriceState();
//            if (ActiveTypeEnum.ENROLL.getValue().equals(activeType) && StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
//                List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceMapper.listByActiveIds(Collections.singletonList(id));
//                if (!CollectionUtils.isEmpty(activeStepPriceSonDtoList)) {
//                    // 将阶梯价格的最高价设置为活动价格显示
//                    tbActivePo.setActivePrice(getMaxStepPrice(activeStepPriceSonDtoList));
//                }
//            }

            // 获取商家id
            BusinessPageVo businessPageVo = businessApi.getById(tbActivePo.getBusinessId()).unpack();
            if (businessPageVo == null) {
                Throw.isBusinessException("商家不存在");
            }

            // 生成分享码
            String shareCode;
            while (true) {
                shareCode = NoUtils.getActiveShareCode();
                Integer count = activeShareMapper.selectCount(new QueryWrapper<TbActiveSharePo>().eq("share_code", shareCode));
                if (count == null || count == 0) {
                    break;
                }
            }

            // 生成小程序分享码
            WxMiniCodeShareTypeEnum wxMiniCodeShareTypeEnum = WxMiniCodeShareTypeEnum.ACTIVE_SHARE;
            String param = wxMiniCodeShareTypeEnum.getName().replace("ACTIVE_ID", String.valueOf(id)).replace("CODE", shareCode);
            // 拼团分享
            if (activeShareDto.getGroupBuyOrderId() != null) {
                param = param.replace("GROUP_ORDER_ID", String.valueOf(activeShareDto.getGroupBuyOrderId()));
            } else {
                param = param.replace("GROUP_ORDER_ID", "");
            }
            String miniImgUrl = "";
            // 拼团页面
            if (activeShareDto.getGroupBuyOrderId() != null) {
                log.info("拼团分享, page:{}, param:{}", Constant.GROUP_INVITE_URL_PAGE, param);
                miniImgUrl = wxConfig.getWxMiniCode(Constant.GROUP_INVITE_URL_PAGE, param, wxMiniCodeShareTypeEnum.getValue(), id + "-" + shareCode);
            } else if (PromotionTypeEnum.GROUP_BUY.name().equals(tbActivePo.getPromotionType())) {
                log.info("拼团分享, page:{}, param:{}", Constant.GROUP_SHARE_URL_PAGE, param);
                miniImgUrl = wxConfig.getWxMiniCode(Constant.GROUP_SHARE_URL_PAGE, param, wxMiniCodeShareTypeEnum.getValue(), id + "-" + shareCode);
            } else {
                miniImgUrl = wxConfig.getWxMiniCode(Constant.ACTIVE_SHARE_URL_PAGE, param, wxMiniCodeShareTypeEnum.getValue(), id + "-" + shareCode);
            }
            if (com.cq.hd.common.utils.StringUtils.isBlank(miniImgUrl)) {
                log.error("生成分享活动小程序码失败,shareCode:{}", shareCode);
                Throw.isBusinessException("邀请失败");
            }

            // 添加活动分享记录数据
            TbActiveSharePo tbActiveSharePo = new TbActiveSharePo();
            tbActiveSharePo.setBusinessId(tbActivePo.getBusinessId());
            tbActiveSharePo.setActiveId(id);
            tbActiveSharePo.setUserId(userId);
            tbActiveSharePo.setAgent1Id(agent1Id);
            tbActiveSharePo.setAgent2Id(agent2Id);
            tbActiveSharePo.setShareCode(shareCode);
            tbActiveSharePo.setMiniImgUrl(miniImgUrl);
            // 0-无，1-佣金，2-其他权益，3-积分
            tbActiveSharePo.setRewardType(type);
            tbActiveSharePo.setShareTime(LocalDateTime.now());
            tbActiveSharePo.setCreateTime(LocalDateTime.now());
            tbActiveSharePo.setUpdateTime(LocalDateTime.now());
            int insert = activeShareMapper.insert(tbActiveSharePo);
            if (insert == 0) {
                Throw.isBusinessException("分享失败");
            }

            activeShareVo.setBusinessShortName(businessPageVo.getBusinessShortName());
            activeShareVo.setNickName(activeShareDto.getNickName());
            activeShareVo.setAvatar(activeShareDto.getAvatar());
            activeShareVo.setActiveTitle(tbActivePo.getActiveTitle());
            activeShareVo.setActiveImg(tbActivePo.getActiveImg());
            activeShareVo.setActivePrice(tbActivePo.getActivePrice());
            activeShareVo.setOriginPrice(tbActivePo.getOriginPrice());
            activeShareVo.setMiniImgUrl(miniImgUrl);
            activeShareVo.setShareCode(shareCode);
            activeShareVo.setBusinessId(tbActiveSharePo.getBusinessId());
            activeShareVo.setLogo(businessPageVo.getLogo());
            activeShareVo.setPosterShowAvatarState(businessPageVo.getPosterShowAvatarState());

            // 如果是拼团活动，则取拼团价格
            if (PromotionTypeEnum.GROUP_BUY.name().equals(tbActivePo.getPromotionType())) {
                TbActiveGroupBuyPo activeGroupBuyPo = activeGroupBuyService.getByActiveId(tbActivePo.getId());
                activeShareVo.setActivePrice(activeGroupBuyPo.getGroupBuyPrice());
            }

            // 分享赚积分
            ShareActivePointsDto shareActivePointsDto = new ShareActivePointsDto();
            shareActivePointsDto.setBusinessId(tbActivePo.getBusinessId());
            shareActivePointsDto.setUserId(userId);
            shareActivePointsDto.setActiveId(tbActivePo.getId());
            shareActivePointsDto.setActiveTitle(tbActivePo.getActiveTitle());
            businessPointsMallApi.getShareActivePoints(shareActivePointsDto);

            return activeShareVo;
        } finally {
            LockUtils.unlock(lockKey);
        }
    }

    @Override
    public String generateShortLink(ActiveShortLinkDto activeShortLinkDto) {
        return wxConfig.generateShortLink(activeShortLinkDto.getPageUrl());
    }

    private BigDecimal getMaxStepPrice(List<ActiveStepPriceSonDto> activeStepPriceSonDtoList) {
        // 倒序阶梯价格，获取阶梯最大价格
        activeStepPriceSonDtoList = activeStepPriceSonDtoList.stream()
                .sorted(Comparator.comparing(ActiveStepPriceSonDto::getEnrollPrice).reversed())
                .collect(Collectors.toList());
        return activeStepPriceSonDtoList.get(0).getEnrollPrice();

//        BigDecimal activePrice = null;
//        for (ActiveStepPriceSonDto activeStepPriceSonDto : activeStepPriceSonDtoList) {
//            BigDecimal enrollPrice = activeStepPriceSonDto.getEnrollPrice();
//            if (activePrice == null || activePrice.compareTo(enrollPrice) > 0) {
//                activePrice = enrollPrice;
//            }
//        }
//        return activePrice == null ? BigDecimal.ZERO : activePrice;
    }

    @Override
    public List<ActivePageVo> listByDto(ActiveDto activeDto) {
        return baseMapper.listByDto(activeDto);
    }

    @Override
    public ActiveVo getActiveById(Long id) {
        TbActivePo activePo = baseMapper.selectById(id);
        if (activePo == null) {
            return null;
        }

        ActiveVo activeVo = new ActiveVo();
        BeanUtils.copyProperties(activePo, activeVo);

        Integer activeType = activePo.getActiveType();
        if (ActiveTypeEnum.GROUP.getValue().equals(activeType)) {
            setGroupGoods4GetActiveById(id, activeVo, activePo);
        } else if (ActiveTypeEnum.ENROLL.getValue().equals(activeType)) {
            setEnrollInfo4GetActiveById(id, activePo, activeVo);
        } else if (ActiveTypeEnum.GROUP_ENROLL.getValue().equals(activeType)) {
            setGroupGoods4GetActiveById(id, activeVo, activePo);
            setEnrollInfo4GetActiveById(id, activePo, activeVo);
        }

        return activeVo;
    }

    private void setEnrollInfo4GetActiveById(Long id, TbActivePo activePo, ActiveVo activeVo) {
        // 如果是报名活动
        // 查找阶梯价格列表
        Integer stepPriceState = activePo.getStepPriceState();
        if (StepPriceStateEnum.YES.getValue().equals(stepPriceState)) {
            List<ActiveStepPriceSonDto> activeStepPriceSonDtoList = activeStepPriceMapper.listByActiveIds(Collections.singletonList(id));
            activeVo.setActiveStepPrices(activeStepPriceSonDtoList);
        }

        // 查找报名信息列表
        List<ActiveEnrollInfoSonDto> activeEnrollInfos = activeEnrollInfoMapper.listByActiveId(id);
        if (!CollectionUtils.isEmpty(activeEnrollInfos)) {
            for (ActiveEnrollInfoSonDto activeEnrollInfo : activeEnrollInfos) {
                if (ActiveEnrollInfoTypeEnum.WRITE.getValue().equals(activeEnrollInfo.getType())) {
                    continue;
                }

                String content = activeEnrollInfo.getContent();
                if (StringUtils.isEmpty(content)) {
                    continue;
                }

                activeEnrollInfo.setActiveEnrollInfoOptions(JSON.parseArray(content, ActiveEnrollInfoOptionDto.class));
                activeEnrollInfo.setContent("");
            }
        }
        activeVo.setActiveEnrollInfos(activeEnrollInfos);
    }

    private void setGroupGoods4GetActiveById(Long id, ActiveVo activeVo, TbActivePo activePo) {
        // 如果是团购活动
        // 查找活动商品列表
        activeVo.setActiveGoods(activeGoodsMapper.listByActiveId(id));

        // 查找多件多折列表
        Integer discountState = activePo.getDiscountState();
        if (DiscountStateEnum.OPEN.getValue().equals(discountState)) {
            activeVo.setActiveDiscount(activeDiscountMapper.listByActiveIds(Collections.singletonList(id)));
        }

        // 查找活动商品补贴列表
        Integer subsidyState = activePo.getSubsidyState();
        if (SubsidyStateEnum.MANUAL.getValue().equals(subsidyState)) {
            activeVo.setActiveGoodsSubsidy(activeGoodsSubsidyMapper.listByActiveId(id));
        }
    }

    @Override
    public Boolean subActiveStock(ActiveSubStockDto activeSubStockDto) {
        Long activeId = activeSubStockDto.getActiveId();
        Integer num = activeSubStockDto.getNum();
        ActiveRedPacketBillPageVo activeRedPacketBillPageVo = activeSubStockDto.getActiveRedPacketBillPageVo();
        List<ActiveGoodsSonDto> activeGoodsSonDtos = activeSubStockDto.getActiveGoodsSonDtos();

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            // 扣减活动库存
            int count = baseMapper.subActiveStock(activeId, num);
            if (count == 0) {
                Throw.isBusinessException("活动库存不足");
            }

            // 更新红包状态=已使用
            if (activeRedPacketBillPageVo != null) {
                count = activeRedPacketBillMapper.updateUseState(activeRedPacketBillPageVo);
                if (count == 0) {
                    Throw.isBusinessException("红包已被使用");
                }
            }

            // 如果是团购活动，则扣减活动对应商品冻结库存
            if (!CollectionUtils.isEmpty(activeGoodsSonDtos)) {
                for (ActiveGoodsSonDto activeGoodsSonDto : activeGoodsSonDtos) {
                    count = activeGoodsStockMapper.subFreezeStock(activeId, activeGoodsSonDto.getGoodsId(), activeGoodsSonDto.getGoodsNum());
                    if (count == 0) {
                        Throw.isBusinessException("活动商品库存不足");
                    }
                }
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<扣减活动库存>事务异常回滚", e);
            return false;
        }

        return true;
    }

    @Override
    public Boolean addActiveStock(ActiveAddStockDto activeAddStockDto) {
        Long activeId = activeAddStockDto.getActiveId();
        Integer num = activeAddStockDto.getNum();
        ActiveRedPacketBillPageVo activeRedPacketBillPageVo = activeAddStockDto.getActiveRedPacketBillPageVo();
        List<ActiveGoodsSonDto> activeGoodsSonDtos = activeAddStockDto.getActiveGoodsSonDtos();

        TransactionStatus transaction = transactionManager.getTransaction(new DefaultTransactionAttribute());

        try {
            // 增加活动库存
            int count = baseMapper.addActiveStock(activeId, num);
            if (count == 0) {
                Throw.isBusinessException("增加活动库存失败");
            }

            // 更新红包状态=未使用
            if (activeRedPacketBillPageVo != null) {
                count = activeRedPacketBillMapper.updateUnUseState(activeRedPacketBillPageVo);
                if (count == 0) {
                    Throw.isBusinessException("更新红包状态失败");
                }
            }

            // 如果是团购活动，则增加活动对应商品冻结库存
            if (!CollectionUtils.isEmpty(activeGoodsSonDtos)) {
                for (ActiveGoodsSonDto activeGoodsSonDto : activeGoodsSonDtos) {
                    count = activeGoodsStockMapper.addFreezeStock(activeId, activeGoodsSonDto.getGoodsId(), activeGoodsSonDto.getGoodsNum());
                    if (count == 0) {
                        Throw.isBusinessException("增加活动商品失败");
                    }
                }
            }

            transactionManager.commit(transaction);
        } catch (Exception e) {
            //回滚事务
            transactionManager.rollback(transaction);
            log.error("<扣减活动库存>事务异常回滚", e);
            return false;
        }

        return true;
    }

    @Override
    public ActiveSimpleVo getSimpleVoById(Long id) {
        TbActivePo activePo = baseMapper.selectById(id);
        if (activePo == null) {
            return null;
        }

        ActiveSimpleVo activeSimpleVo = new ActiveSimpleVo();
        BeanUtils.copyProperties(activePo, activeSimpleVo);

        return activeSimpleVo;
    }

    @Override
    public Boolean scanActiveJob() {
        // 扫描未开始和进行中的活动
        //      如果未开始的活动开始时间早于当前时间，活动结束时间晚于当前时间，则更新为进行中
        //      如果未开始的活动结束时间早于当前时间，则更新为已结束
        //      如果进行中的活动结束时间早于当前时间，则更新为已结束

        List<TbActivePo> tbActivePos = baseMapper.selectList(new QueryWrapper<TbActivePo>()
                .in("active_state", Arrays.asList(ActiveStateEnum.NO_START.getValue(), ActiveStateEnum.IN_PROGRESS.getValue())));
        if (CollectionUtils.isEmpty(tbActivePos)) {
            return true;
        }

        LocalDateTime now = LocalDateTime.now();
        for (TbActivePo tbActivePo : tbActivePos) {
            Integer activeState = tbActivePo.getActiveState();
            LocalDateTime startTime = tbActivePo.getStartTime();
            LocalDateTime endTime = tbActivePo.getEndTime();

            if (!endTime.isAfter(now)) {
                // 更新为已结束
                tbActivePo.setActiveState(ActiveStateEnum.ENDED.getValue());
                tbActivePo.setUpdateTime(now);
                baseMapper.updateById(tbActivePo);

                // 通知订单服务活动结束
                orderApi.onActiveEnd(tbActivePo.getId());

                // 如果是团购活动，需要将活动商品剩余库存释放
                if (tbActivePo.getDelState() == 0
                        && (ActiveTypeEnum.GROUP.getValue().equals(tbActivePo.getActiveType())
                            || ActiveTypeEnum.GROUP_ENROLL.getValue().equals(tbActivePo.getActiveType()))) {
                    List<TbActiveGoodsStockPo> activeGoodsStockPos = activeGoodsStockMapper.selectList(new QueryWrapper<TbActiveGoodsStockPo>()
                            .eq("active_id", tbActivePo.getId()));
                    if (!CollectionUtils.isEmpty(activeGoodsStockPos)) {
                        for (TbActiveGoodsStockPo activeGoodsStockPo : activeGoodsStockPos) {
                            Long goodsId = activeGoodsStockPo.getGoodsId();
                            Integer freezeStock = activeGoodsStockPo.getFreezeStock();

                            if (freezeStock > 0) {
                                goodsMapper.addStock(goodsId, freezeStock);

                                activeGoodsStockPo.setFreezeStock(0);
                                activeGoodsStockPo.setUpdateTime(now);
                                activeGoodsStockMapper.updateById(activeGoodsStockPo);
                            }
                        }
                    }
                }

                continue;
            }

            if (ActiveStateEnum.NO_START.getValue().equals(activeState) && startTime.isBefore(now) && endTime.isAfter(now)) {
                // 更新为进行中
                tbActivePo.setActiveState(ActiveStateEnum.IN_PROGRESS.getValue());
                tbActivePo.setUpdateTime(now);
                baseMapper.updateById(tbActivePo);
            }
        }

        return true;
    }

    @Override
    public Integer getCountByDate(String startTime, String endTime) {
        QueryWrapper<TbActivePo> queryWrapper = new QueryWrapper<TbActivePo>().eq("del_state", 0);
        if (!StringUtils.isEmpty(startTime)) {
            queryWrapper.ge("release_time", startTime);
        }

        if (!StringUtils.isEmpty(endTime)) {
            queryWrapper.le("release_time", endTime);
        }
        return baseMapper.selectCount(queryWrapper);
    }

    @Override
    public Boolean updateActiveState(UpdateActiveStateDto updateActiveStateDto) {
        Long id = updateActiveStateDto.getId();
        if (id == null || id <= 0) {
            Throw.isBusinessException("请选择活动");
        }

        TbActivePo activePo = baseMapper.selectById(id);
        Integer activeState = activePo.getActiveState();
        if (ActiveStateEnum.NO_RELEASE.getValue().equals(activeState)) {
            return true;
        }

        LocalDateTime now = LocalDateTime.now();

        LocalDateTime startTime = activePo.getStartTime();
        LocalDateTime endTime = activePo.getEndTime();
        if (startTime.compareTo(now) > 0) {
            activeState = ActiveStateEnum.NO_START.getValue();
        } else if (endTime.compareTo(now) <= 0) {
            activeState = ActiveStateEnum.ENDED.getValue();
        } else if (startTime.compareTo(now) <= 0 && endTime.compareTo(now) > 0) {
            activeState = ActiveStateEnum.IN_PROGRESS.getValue();
        }

        if (ActiveStateEnum.ENDED.getValue().equals(activeState)) {
            baseMapper.updateState(updateActiveStateDto);
        }

        return true;
    }

    @Override
    public Set<String> listCityName() {
        return baseMapper.listCityName();
    }

    // 设置活动类型
    private void setActiveType(ActiveReleaseDto activeReleaseDto) {
        // 3-外部活动，不处理
        if (activeReleaseDto.getActiveType() != null
                && activeReleaseDto.getActiveType().equals(ActiveTypeEnum.EXTERNAL.getValue())) {
            return;
        }
        Integer enrollEnable = Optional.ofNullable(activeReleaseDto.getEnrollEnable()).orElse(0);
        if (!CollectionUtils.isEmpty(activeReleaseDto.getActiveGoods()) && enrollEnable.equals(0)) {
            // 1-团购活动：有团购商品 & 报名未开启
            activeReleaseDto.setActiveType(ActiveTypeEnum.GROUP.getValue());
        } else if (CollectionUtils.isEmpty(activeReleaseDto.getActiveGoods()) && enrollEnable.equals(1)) {
            // 2-报名活动：无团购商品 & 报名开启
            activeReleaseDto.setActiveType(ActiveTypeEnum.ENROLL.getValue());
        } else if (!CollectionUtils.isEmpty(activeReleaseDto.getActiveGoods()) && enrollEnable.equals(1)) {
            // 4-团购+报名活动：有团购商品 & 报名开启
            activeReleaseDto.setActiveType(ActiveTypeEnum.GROUP_ENROLL.getValue());
        }
    }

}
